I have a project where by I used a sorting algorithm to sort an array but I am at the point where I now need to examine different arrays of different sizes and different values. Is there a way I can assign an array to a global array using a for loop
e.g
I have 12 arrays named array1 through to array12 and i need to assign them to a global array called array that is passed in to the sorting algorithm
The 12 arrays are passed in to the array from a file
Having variables that look like array1, array2, array3,..., array12 is a sure sign that you need a single array instead of all these variables. You should put these arrays into an array of arrays, and use array[x] to access them.
For example, instead of
int[] array1 = new int[] {1, 2, 3};
int[] array2 = new int[] {4, 5, 6};
...
int[] array12 = new int[] {34, 35, 36};
you would write
int[][] array = new int[][] {
new int[] {1, 2, 3},
new int[] {4, 5, 6},
...
new int[] {34, 35, 36}
};
Now instead of writing array5 you would write array[4] (4, not 5, because indexes of Java arrays are zero-based). This indexing can be done with a for loop:
int[][] array = new int[][] { ... };
for (int i = 0 ; i != array.length ; i++) {
callMySort(array[i]);
}
or from a foreach loop:
int[][] array = new int[][] { ... };
for (int[] sortMe : array) {
callMySort(sortMe);
}
Related
I'm trying to slice the columns or rows of a 2d Integer Array in Java.
I tried the following syntax array[:][0] or array[0][:] to get the first column/row. I get an error, so most probably this is not the correct syntax in Java. Is it possible to slice in any case a specific column/row in Java?
If I'm not mistaken, slicing in Python corresponds to extracting a subarray from the given array, so if you have an array like below:
int[][] vet = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Performing the following slicing vet[0:3][1] corresponds to retrieve an array with the elements 2, 5, 8 (second column from row 0 included to row 3 excluded).
Unfortunately, in Java this is not possible, at least not "vertically" since a 2D array is basically an array of arrays. Each "row" index identifies a sub-array but in reality there are now actual rows or columns, just arrays within another array.
What you could do is to use the Arrays.copyOfRange() method to slice an array "horizontally".
Integer[][] vet = new Integer[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Integer[] subArray = new Integer[3];
subArray = Arrays.copyOfRange(vet[1], 0, 3); //Retrieves the elements [4, 5, 6]
Instead, for slicing "vertically" you need to write a utility method:
public static void main(String[] args) {
Integer[][] vet = new Integer[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Integer[] subArray = new Integer[3];
verticalSlicing(vet, subArray, 1, 0, 3);
System.out.println(Arrays.toString(subArrayVert)); //Prints [2, 5, 8]
}
public static <T> void verticalSlicing(T[][] vet, T[] subArray, int col, int rowStart, int rowEnd) {
if (col < 0 || col > subArray.length || (rowEnd - rowStart) > subArray.length) {
return;
}
IntStream.range(rowStart, rowEnd).forEach(i -> subArray[i] = vet[i][col]);
}
Usually a 2d array in java will look something like this:
double[][] doubleArray = new double[3][4];
So getting the first row can be:
double[] firstRow = doubleArray[0];
And getting the first column can look like this:
double[] firstColumn = new double[doubleArray.length];
for (int i = 0; i < doubleArray.length; i++) {
firstColumn[i] = doubleArray[i][0];
}
Given that you index array[x][y] you can get column x by:
int column[] = array[x].
To get row y:
int row[] = new int[array.length];
for (int i = 0; i < array.length; i++) {
row[i] = array[i][y];
}
I have an integer array.
int[] arr1 = new int[] {3, 4, 5};. I want to insert this array when initializing another array. So that when
int[] arr2 = new int[] {8, 7, arr1, 1, 0};, arr2 will equal {8, 7, 3, 4, 5, 1, 0}.
Also, I do not know the length of arr1, so I can't do int[] arr2 = new int[] {8, 7, arr1[0], arr1[1], arr1[2], 1, 0};
Any help is greatly appreciated.
Sadly as far as I'm aware something like that can't be done in a single operation. The best I was able to come up with is to create a result array. Then you copy to it first part of arr2, whole arr1 and finally second part of arr2. In the end whole method would look like so:
private static int[] insertArrayAtPosition(int[] arr1, int[] arr2, int insertPos){
int[] result = new int[arr1.length + arr2.length];
System.arraycopy(arr2, 0, result, 0, insertPos);
System.arraycopy(arr1, 0, result, insertPos, arr1.length);
System.arraycopy(arr2, insertPos, result, insertPos + arr1.length, arr2.length - insertPos);
return result;
}
And then you can call it like so:
public static void main(String args[]) {
int[] arr1 = new int[] {3, 4, 5};
int[] arr2 = new int[] {8, 7, 1, 0};
int[] result = insertArrayAtPosition(arr1, arr2, 2);
System.out.println(Arrays.toString(result));
}
Edit: Milgo's solution looks much better. However, mine allows to insert one array into another at specific position after they are already created. Which one to use depeds on the usecase.
You could use ArrayUtils.addAll() three times.
int[] arr1 = new int[] {3, 4, 5};
int[] arr2 = new int[arr1.length + 4];
ArrayUtils.addAll(arr2, new int[]{8, 7});
ArrayUtils.addAll(arr2, arr1);
ArrayUtils.addAll(arr2, new int[]{1, 0});
ArrayUtils is part of Apache Commons.
This is not natively supported in java / there is no language feature that allows you to use a one liner.
You can of course write a loop that inserts the elements of the other array, you can also use list interfaces or Arrays#stream. The best way to do it should probably be to use lists, like this:
List<Integer> arr1 = Arrays.asList(3, 4, 5);
List<Integer> arr2 = Arrays.asList(8, 7, 1, 0);
arr2.addAll(2, arr1);
Hope this helpes.
Edit: It is a one liner btw :)
public class Main {
public static void main(String[] args) {
int[][] numbers = {{1, 2, 3} , {4, 5, 6, 7}}; //Is it defined?
int x = numbers[0][3]; // Should the output be 0?
System.out.println(x);
}
}
you may take a look here into the official oracle specification:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
When you take a look on chapter (array access) you will see that:
"All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1."
A 2D array is really an array of arrays. So you can do this.
int[][] arr = new int[4][];
arr[0] = new int[] {1,2,3};
arr[1] = new int[] {4,5,6,7};
arr[2] = new int[] {8,9,10,11,12,13};
arr[3] = new int[] {14,15};
And to print them.
for (int[] a : arr) {
System.out.println(Arrays.toString(a));
}
Prints
[1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11, 12, 13]
[14, 15]
Technically, there are no two-dimensional arrays. What you can have is an array of arrays; this is conveyed precisely by the [][] syntax.
In your example,
int[][] numbers = {{1, 2, 3} , {4, 5, 6, 7}};
the 0'th element of numbers, i.e., numbers[0], is a 3-element array, whereas numbers[1], is a 4-element array.
Accessing numbers[0][3] will raise an exception, since 3 is out of bounds for the 3-element array.
Reference to Java Language Specification: Chapter 10, Arrays.
I am trying to access an array based on a number. Let me explain:
stringBuilder.append(array1[i]);
but I have 4 arrays, I would like to access the array like this:
int i;
int aNum;
stringBuilder.append(array(aNum)[i]);
so the array number selected depends on the value of aNum (1 - 4) where [i] being the location of the array (0 - n)
This code however doesn't work. Any ideas? Tried looking on google but can't find the correct code I need. It does seem simple but can't find the solution. Hope it makes sense!
You are referring to a two-dimensional array, which is an array of arrays. Here is an example:
/**
<P>{#code java TwoDArray}</P>
**/
public class TwoDArray {
public static final void main(String[] ignored) {
//Setup
int[][] intArrArr = new int[4][];
intArrArr[0] = new int[] {1, 2, 3, 4};
intArrArr[1] = new int[] {5, 6, 7, 8};
intArrArr[2] = new int[] {9, 10, 11, 12};
intArrArr[3] = new int[] {13, 14, 15, 16};
StringBuilder stringBuilder = new StringBuilder();
//Go
int indexOfIntInSelectedArray = 1; //The second element...
int indexOfArray = 2; //...in the third array.
stringBuilder.append(intArrArr[indexOfArray][indexOfIntInSelectedArray]);
//Output
System.out.println("stringBuilder.toString()=" + stringBuilder.toString());
}
}
Output:
[C:\java_code\]java TwoDArray
stringBuilder.toString()=10
Arrays can contain theoretically contain any number of dimensions:
https://www.google.com/search?q=multi+dimensional+array+java
https://www.google.com/search?q=three+dimensional+array+java
https://www.google.com/search?q=four+dimensional+array+java
Your array is a two dimensional array (array of arrays). You need to index using two pairs of brackets:
int rows = 4;
int cols = 5;
int[][] myArray = new int[rows][cols];
int row;
int col;
stringBuilder.append(myArray[row][col]);
Say I have less than ten two dimensional arrays representing matrices in java. Each array is enumerated from 0 to 6. Each array is n*2^enumval larger where n is the number of elements from the 0th enumerated array, thus my multidimensional will almost be pyramid shaped, hence the need for a jagged three dimensional array. Is it possible to create a jagged three dimensional array?
int[][] array0 = new int[2][2];
int[][] array1 = new int[4][4];
int[][] array2 = new int[8][8];
int[][] array3 = new int[16][16];
int[][][] arrayStorage = new int[][][];
I would like to to store the arrays with the following approach: arrayStorage[columnOfArray#][rowOfArray#][#]
Yes, it's perfectly possible to create a jagged array in Java.
Here's some sample syntax for it:
int[][] jagged = new int[3][];
jagged[0] = new int[]{1, 2, 4};
jagged[1] = new int[]{9, 17, 35, 80};
jagged[2] = new int[]{100};
In this, I have a jagged array with three rows but an indeterminate amount of columsn. THeir lengths vary from 1 to 4.
Java only supports jagged arrays. An example of the sort of 3D array (using a "list" of "matrices" as a more relatable concrete example) you're looking for:
// an array of m*n (or jagged) 2D arrays.
int[][][] matrices = new int[2][][];
// A 2*2 matrix
int[][] matrix22 = new int[2][];
matrix22[0] = new int[] {1, 2};
matrix22[1] = new int[] {3, 4};
matrices[0] = matrix22;
// A 3*3 matrix
int[][] matrix33 = new int[3][];
matrix33[0] = new int[] {1, 2, 3};
matrix33[1] = new int[] {4, 5, 6};
matrix33[2] = new int[] {7, 8, 9};
matrices[1] = matrix33;
Or, golfed to one statement:
int[][][] matrices2 = new int[][][] {
new int[][] {
new int[] {1, 2},
new int[] {3, 4}
},
new int[][] {
new int[] {1, 2, 3},
new int[] {4, 5, 6},
new int[] {7, 8, 9}
}
};