Getting the array length of a 2D array in Java - java

I need to get the length of a 2D array for both the row and column. I’ve successfully done this, using the following code:
public class MyClass {
public static void main(String args[])
{
int[][] test;
test = new int[5][10];
int row = test.length;
int col = test[0].length;
System.out.println(row);
System.out.println(col);
}
}
This prints out 5, 10 as expected.
Now take a look at this line:
int col = test[0].length;
Notice that I actually have to reference a particular row, in order to get the column length. To me, this seems incredibly ugly. Additionally, if the array was defined as:
test = new int[0][10];
Then the code would fail when trying to get the length. Is there a different (more intelligent) way to do this?

Consider
public static void main(String[] args) {
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
System.out.println(foo.length); //2
System.out.println(foo[0].length); //3
System.out.println(foo[1].length); //4
}
Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.

A 2D array is not a rectangular grid. Or maybe better, there is no such thing as a 2D array in Java.
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
int[][] test;
test = new int[5][];//'2D array'
for (int i=0;i<test.length;i++)
test[i] = new int[i];
System.out.println(Arrays.deepToString(test));
Object[] test2;
test2 = new Object[5];//array of objects
for (int i=0;i<test2.length;i++)
test2[i] = new int[i];//array is a object too
System.out.println(Arrays.deepToString(test2));
}
}
Outputs
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
The arrays test and test2 are (more or less) the same.

It was really hard to remember that
int numberOfColumns = arr.length;
int numberOfRows = arr[0].length;
Let's understand why this is so and how we can figure this out when we're given an array problem. From the below code we can see that rows = 4 and columns = 3:
int[][] arr = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3} };
arr has multiple arrays in it, and these arrays can be arranged in a vertical manner to get the number of columns. To get the number of rows, we need to access the first array and consider its length. In this case, we access [1, 1, 1, 1] and thus, the number of rows = 4. When you're given a problem where you can't see the array, you can visualize the array as a rectangle with n X m dimensions and conclude that we can get the number of rows by accessing the first array then its length. The other one (arr.length) is for the columns.

Java allows you to create "ragged arrays" where each "row" has different lengths. If you know you have a square array, you can use your code modified to protect against an empty array like this:
if (row > 0) col = test[0].length;

If you have this array:
String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}},
{{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};
You can do this:
example.length;
= 2
example[0].length;
= 2
example[1].length;
= 2
example[0][1].length;
= 3
example[1][0].length;
= 4

There's not a cleaner way at the language level because not all multidimensional arrays are rectangular. Sometimes jagged (differing column lengths) arrays are necessary.
You could easy create your own class to abstract the functionality you need.
If you aren't limited to arrays, then perhaps some of the various collection classes would work as well, like a Multimap.

.length = number of rows / column length
[0].length = number of columns / row length

Example Array 1:
int arr[][] = { { 1, 3, 1, 5 },
{ 2, 2, 4, 1 },
{ 5, 0, 2, 3 },
{ 0, 6, 1, 2 } };
Example Array 2:
int arr[][] = { { 1, 3, 1 },
{ 2, 2, 4 },
{ 5, 0, 2 },
{ 0, 6, 1 } };
Below function will work for any Symmetric and Asymmetric Array Matrix
row_Count = arr.length
column_Count = arr[0].length

Try this following program for 2d array in java:
public class ArrayTwo2 {
public static void main(String[] args) throws IOException,NumberFormatException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[][] a;
int sum=0;
a=new int[3][2];
System.out.println("Enter array with 5 elements");
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
System.out.print(a[i][j]+" ");
sum=sum+a[i][j];
}
System.out.println();
//System.out.println("Array Sum: "+sum);
sum=0;
}
}
}

import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
double[][] test = { {100}, {200}, {300}, {400}, {500}, {600}, {700}, {800}, {900}, {1000}};
int [][] removeRow = { {0}, {1}, {3}, {4}, };
double[][] newTest = new double[test.length - removeRow.length][test[0].length];
for (int i = 0, j = 0, k = 0; i < test.length; i++) {
if (j < removeRow.length) {
if (i == removeRow[j][0]) {
j++;
continue;
}
}
newTest[k][0] = test[i][0];
k++;
}
System.out.println(Arrays.deepToString(newTest));
}
}

With Java 8, allow you doing something more elegant like this:
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
int length = Arrays.stream(array).max(Comparator.comparingInt(ArrayUtils::getLength)).get().length

int rows=arr.length; //For knowing No of rows
int cols=arr[0].length; //For Knowing No of columns
Run This code... and Understand...
public class Store2darrays {
public static void main(String args[]) {
int[]arr={1,2,3,4};
System.out.println(arr.length);
int[][] arr2d={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
System.out.println(arr2d.length);
System.out.println(arr2d);
System.out.println(arr2d[0]);
System.out.println(arr2d[1]);
System.out.println(arr2d.length);
System.out.println(arr2d[0].length); }
}

public class Array_2D {
int arr[][];
public Array_2D() {
Random r=new Random(10);
arr = new int[5][10];
for(int i=0;i<5;i++)
{
for(int j=0;j<10;j++)
{
arr[i][j]=(int)r.nextInt(10);
}
}
}
public void display()
{
for(int i=0;i<5;i++)
{
for(int j=0;j<10;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}
}
public static void main(String[] args) {
Array_2D s=new Array_2D();
s.display();
}
}

Related

How to get output and get sum of columns in array / matrix?

hello to all you code geniuses on here
ill try to explain my problem as simply as i can
image1
To produce image1, lets say an array like below is required, keeping in mind that the numbers are placed left to right in the first row, then go backwards in the second row, and if you added more numbers, it would create a third row.
int[] something = {1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2}
so i want to make to make a "map" of the layout, like this desired output below.
2 1 1 3 3 1
1 2 3 2 1 2
and then from there i would want to find the total for each column, so like this.
2 1 1 3 3 1
1 2 3 2 1 2
..................
3 3 4 5 4 3
(and i then want to make store this layout and sum within another array)
hopefully that all made sense, if so,
how could i go about doing this?
thanks heaps : )
Seems like you can use a two-dimensional array data structure to solve this:
int[][] something = new int[][]{
{2, 1, 1, 3, 3, 1},
{1, 2, 3, 2, 1, 2}
};
int totalForColomn1 = something[0][0] + something [1][0];
int totalForColomn2 = something[0][1] + something [1][1];
// ...
int totoalForColomn6 = something[0][5] + something [1][5];
If you could only use one-dimensional array:
int[] something = new int[] {2, 1, 1, 3, 3, 1, 4, 2, 3, 2, 1, 2};
int row_size = 6;
int totalForColomn1 = something[0] + something[0 + row_size];
int totalForColomn2 = something[1] + something[1 + row_size];
// ...
int totalForColomn6 = something[5] + something[5 + row_size];
Remember to keep a consistant row_size by putting those undecided element to 0.
In this case, you should init your array like:
int[] something = new int[] {0, 0, 0, 0, 1, 4, 1, 2, 3, 2, 1, 1};
So If I am reading this correctly if L is the length of your array you want to add the nth and L-1-nth element of the array and store the result in an array. I through this together quickly so I did not handle what happens if the input array is of odd length (your question did not specify).
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] something = {1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2};
System.out.println(Arrays.toString(addValues(something)));
}
public static int [] addValues(int [] input){
int[] output = new int[input.length / 2];
for(int i = 0; i<input.length/2; i++){
output[i] = input[i] + input[input.length -1 - i ];
}
return output;
}
}
EDIT:
I think this will work for the case where the are an arbitrary number of rows.
The main insite into how this work is in the grid below.
0 1 2 3 4 5 :row 0
11 10 9 8 7 6 :row 1
12 13 14 15 16 17:row 2
23 22 21 20 19 18:row 3
So whether the output index is going up or down is determined by the row number and every time we hit an input index that is the same size as our output array we need to stay at the same output index.
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] something = { 1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2 };
System.out.println(Arrays.toString(addValues(something, 6)));
}
public static int[] addValues(int[] input, int row_lenth) {
int[] output = new int[row_lenth];
int output_index = 0;
for (int i = 0; i < input.length; i++) {
if (i % row_lenth != 0) {
if ((i / row_lenth) % 2 == 0) {
output_index++;
} else {
output_index--;
}
}
output[output_index] += input[i];
}
return output;
}
}
import java.util.Scanner;
public class Stckoverq {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
System.out.print("What is the size of array? ");
int size = sn.nextInt();
System.out.print("What is length of the row?");
int len = sn.nextInt();
int ind = 0, i = 0, j = 0;
//variable 'ind' is for getting the element from arr[] array at index ind
int rac[][] = new int[size/len][len];
//variable 'i' and 'j' is for storing rows and column elements respectively in array rac[]
int arr[] = new int[size];
System.out.println("Enter array elements: ");
for(int k=0;k<size;k++)
arr[k] = sn.nextInt();
while(ind!=arr.length)
{
if(j==len) {
j=0; //Reset column index
i++; //Increase row index
}
rac[i][j] = arr[ind];
ind++;
j++; //Increase column index
}
//Now print the rows and columns................
for(int r =0;r<size/len;r++) {
for(int c=0;c<len;c++)
System.out.print(rac[r][c]+"\t");
System.out.println();
}
int sum[] = new int[len];
//this array sum[] is used to store sum of all row elements.
int s = 0;
for(int c=0;c<len;c++) {
for(int r =0;r<size/len;r++)
s += rac[r][c];
sum[c] = s;
s = 0;
}
for(int x: sum)
System.out.print(x+"\t");
}
}

Sort array in a specific order in java

I am trying to sort an array to a specific order. So for example, I have this array
{6,1,1,5,6,1,5,4,6}
and I want them to be sorted to this order
{4,1,6,5}
expected new array would be
{4,1,1,1,6,6,6,6,5}
My idea is this,
public class Sort {
static int[] list = { 6, 1, 1, 5, 6, 1, 6, 4, 6 };
static int[] sorted = { 4, 1, 6, 5 };
static int[] newList = new int[list.length];
static int count = 0;
public static void main(String[] args) {
for (int i = 0; i < sorted.length; i++) {
for (int j = 0; j < list.length; j++) {
if (list[j] != sorted[i])
continue;
else
newList[count++] = sorted[i];
}
}
}
}
It works fine, however, I am not sure if this is the fastest and easier way to do this regarding speed and memory cause the list could have too many numbers.
You can use java built-in sort algorithm with a customized comparator.
public static void main(String[] args) {
Integer[] list = { 6, 1, 1, 5, 6, 1, 6, 4, 6 };
int[] sorted = { 4, 1, 6, 5 };
Map<Integer, Integer> order = new HashMap<>();
for (int i = 0; i < sorted.length; i++)
order.put(sorted[i], i);
Arrays.sort(list, (a ,b) -> order.get(a) - order.get(b));
System.out.println(Arrays.toString(list));
}
The output is [4, 1, 1, 1, 6, 6, 6, 6, 5].
If you
know the possible elements in advance
and they are relatively small numbers
you can simply count them:
int stats[]=new int[7]; // "largest possible element"+1
for(int i=0;i<list.length;i++)
stats[list[i]]++;
and then reconstruct the ordered list:
int idx=0;
for(int i=0;i<sorted.length;i++){
int val=sorted[i];
for(int j=stats[val];j>0;j--)
newlist[idx++]=val;
The two snippets in total have "2*list.length" steps, which is probably faster than your original "sorted.length*list.length" loop-pair.
As you have not described the actual use-case, it is hard to tell more. For example if you have these numbers only, you probably do not need the ordered result to be an actual list. However if these numbers are just part of an object, this build-a-statistics approach is not applicable.

How to work with arrays within arrays in java?

Let's say I have an int[][] anArray = new int[4][4];
And let's say that I wanted to make row 3 of anArray {1, 2, 3, 4}. Could I do that without manually assigning each individual value its value? What if it was column 2 of anArray?
I'm posting this because it's rather inconvenient to do stuff like this:
int[][] foo = new int[bar][baz];
//
//Code that uses other columns of foo
//
for (int n=0; n < bar; n++)
foo[n][1] = bin[n];
If I understand your question correctly, here is the code to assign row index 3 of anArray as {1,2,3,4} without loops:
int[][] anArray = new int[4][4];
anArray[3] = new int[] {1,2,3,4};
System.out.println(Arrays.deepToString(anArray));
Output:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 4]]
If you want to assign the entire row of a two-dimensional array to another (one-dimensional) array, you can simply do
int[][] foo = new int [3][3];
int[] bin={1,2,3};
foo[1] = bin;
If want to assign the column though, I am afraid that you can only do it manually...
anArray[3] = new int [] {1, 2, 3, 4}
It is basically an array of arrays and so we can add full arrays in one go:
int[][] array = new int[4][4];
for (int i = 0; i < array.length; i++) {
array[i] = new int[] { 1, 2, 3, 4 };
}
You can use a helper method to set a column:
public class MatrixTest {
public static void main(String... args) {
Integer[][] target = new Integer[3][2];
setMatrixColumn( target, 1, new Integer[]{ 1, 1, 1 } );
System.out.println( Arrays.deepToString( target ) );
}
public static <T> void setMatrixColumn(T[][] matrix, int index, T[] values) {
for ( int i = 0; i < values.length; i++ )
matrix[i][index] = values[index];
}
}

Adding blank rows to a 2d array in Java

Say I have the following 2d array in Java set to a variable named myMap:
1 3 1
3 2 3
1 3 1
The next step in my program is to add rows and columns of zeros as follows:
1 0 3 0 1
0 0 0 0 0
3 0 2 0 3
0 0 0 0 0
1 0 3 0 1
Basically, I'm adding arrays of zero into the spaces between the previous rows/columns. I then fill them in with appropriate numbers (irrelevant to my question) and repeat the process (adding more rows/columns of zeros) a finite number of times.
My question is as follows- what is the easiest and most efficient way to do this in Java? I know I could create a new 2d array and copy everything over, but I feel like there may be a more efficient way to do this. My intuition says that a 2d ArrayList may be the better way to go.
Also, and this my be important, when my program begins, I DO know what the maximum size this 2d array. Also, I cannot expect the symmetry of the numbers that I put in for this example (these were just put in for a good visual reference).
Here's a solution with ArrayLists: (test included)
int[][] ar = new int[][]
{
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 } };
ArrayList<ArrayList<Integer>> a = new ArrayList<>(ar.length);
ArrayList<Integer> blankLine = new ArrayList<>(ar.length * 2 - 1);
for (int i = 0; i < ar.length * 2 - 1; i++)
{
blankLine.add(0);
}
for (int i = 0; i < ar.length; i++)
{
ArrayList<Integer> line = new ArrayList<>();
for (int j = 0; j < ar[i].length; j++)
{
line.add(ar[i][j]);
if (j != ar[i].length - 1)
line.add(0);
}
a.add(line);
if (i != ar.length - 1)
a.add(blankLine);
}
for (ArrayList<Integer> b : a)
{
System.out.println(b);
}
Output:
[0, 0, 1, 0, 2]
[0, 0, 0, 0, 0]
[3, 0, 4, 0, 5]
[0, 0, 0, 0, 0]
[6, 0, 7, 0, 8]
Algorithm
int[][] appendRows(int[][] bag, int[]... rows) {
int[][] extendedBag = new int[bag.length + rows.length][];
int i = 0;
for (int[] row : bag) { fillRow(extendedBag, row, i++); }
for (int[] row : rows) { fillRow(extendedBag, row, i++); }
return extendedBag;
}
// WHERE #fillRow(int[][], int[], int) =
void fillRow(int[][] bag, int[] row, int i) {
bag[i] = new int[row.length];
System.arraycopy(row, 0, bag[i++], 0, row.length);
}
Demo
import java.util.Arrays;
/** Utilities for 2D arrays. */
public class Array2dUtils {
public static void main(String[] args) {
int[][] bag = new int[][] {
{ 0 },
{ 1, 1 },
{ 2, 2, 2 }
};
int[] row1 = new int[] { 3, 3};
int[] row2 = new int[] { 4 };
int[][] biggerBag = appendRows(bag, row1, row2);
System.out.println("Bag:\n" + toString(bag));
System.out.println("Bigger Bag:\n" + toString(biggerBag));
}
/** Append one or more rows to a 2D array of integers. */
public static int[][] appendRows(int[][] bag, int[]... rows) {
int[][] extendedBag = new int[bag.length + rows.length][];
int i = 0;
for (int[] row : bag) { fillRow(extendedBag, row, i++); }
for (int[] row : rows) { fillRow(extendedBag, row, i++); }
return extendedBag;
}
/* fill i-th item of the bag */
private static void fillRow(int[][] bag, int[] row, int i) {
bag[i] = new int[row.length];
System.arraycopy(row, 0, bag[i++], 0, row.length);
}
/** Pretty-prints a 2D array of integers. */
public static String toString(int[][] bag) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bag.length; ++i) {
sb.append(Arrays.toString(bag[i])).append("\n");
}
return sb.toString();
}
}
$ javac Array2dUtils.java
$ java -cp "." Array2dUtils
Bag:
[0]
[1, 1]
[2, 2, 2]
Bigger Bag:
[0]
[1, 1]
[2, 2, 2]
[3, 3]
[4]

Question about permute-by-sorting

In the book "Introduction to Algorithms", second edition, there is the following problem:
Suppose we have some array:
int a[] = {1,2,3,4}
and some random priorities array:
P = {36,3,97,19}
and the goal is to permute the array a randomly using this priorities array.
This is the pseudo code:
PERMUTE-BY-SORTING (A)
1 n ← length[A]
2 for i ← 1 to n
3 do P[i] = RANDOM (1, n 3)
4 sort A, using P as sort keys
5 return A
The result should be the permuted array:
B={2, 4, 1, 3};
I have written this code:
import java.util.*;
public class Permute {
public static void main (String[] args) {
Random r = new Random();
int a[] = new int[] {1,2,3,4};
int n = a.length;
int b[] = new int[a.length];
int p[] = new int[a.length];
for (int i=0; i<p.length; i++) {
p[i] = r.nextInt(n*n*n) + 1;
}
// for (int i=0;i<p.length;i++){
// System.out.println(p[i]);
//}
}
}
How do I continue?
I'm not sure which part you're having trouble with, but essentially this is what happened:
int[] a = { 1, 2, 3, 4 };
int[] p = { 36, 3, 97, 19 };
However you think about it, essentially we want to "zip" the elements of these two lists together. So at the abstract level, we have the following:
Pair<int,int> zipped = { ( 1,36), ( 2, 3), ( 3,97), ( 4,19) };
Now we sort zipped by the second value in the Pair. Whatever sorting algorithm works; it doesn't really matter.
zipped = { ( 2, 3), ( 4,19), ( 1,36), ( 3,97) };
We then unzip the pairs to get the permuted a:
a = { 2, 4, 1, 3 };
p = { 3, 19, 36, 97 };
How to implement
The zip-into-Pair-then-unzip works just fine. Otherwise, you can modify the sorting algorithm so that whenever it moves elements of p[i] to p[j], it also moves a[i] to a[j] to keep both arrays "in-sync".
Java snippet
In the following snippet, the priorities array is hardcoded to the above values. You already figured out how to seed it with random numbers.
import java.util.*;
public class PermuteBySorting {
public static void main(String[] args) {
class PrioritizedValue<T> implements Comparable<PrioritizedValue<T>> {
final T value;
final int priority;
PrioritizedValue(T value, int priority) {
this.value = value;
this.priority = priority;
}
#Override public int compareTo(PrioritizedValue other) {
return Integer.valueOf(this.priority).compareTo(other.priority);
}
}
int[] nums = { 1, 2, 3, 4 };
int[] priorities = { 36, 3, 97, 19 };
final int N = nums.length;
List<PrioritizedValue<Integer>> list =
new ArrayList<PrioritizedValue<Integer>>(N);
for (int i = 0; i < N; i++) {
list.add(new PrioritizedValue<Integer>(nums[i], priorities[i]));
}
Collections.sort(list);
int[] permuted = new int[N];
for (int i = 0; i < N; i++) {
permuted[i] = list.get(i).value;
}
System.out.println(Arrays.toString(permuted));
// prints "[2, 4, 1, 3]"
}
}

Categories