I want to create 2 cells in the first array, but in the second array, I want to have 4 cells.
Is that possible in Java and is it logical?
Example:
public void stack(){
int a[][] = {{2,5234},{5,33,345,45}};
}
Yes this is possible:
int[][] a = new int[2][];
a[0] = {2, 5234};
a[1] = {5, 33, 345, 45};
Or if you want to inline the entire definition:
int[][] a = new int[][]{{2, 5234}, {5, 33, 345, 45}};
This is known as a "jagged array." If you wanted to declare the sizes of these, you could start off with the 2D array declaration:
int[][] a = new int[2][];
and then you can make the length whatever you please
a[0] = new int[2];
a[1] = new int[4];
Essentially the second dimensions of the arrays are arrays themselves. You can write explicitly what you want as:
a[0] = [2, 5234];
a[1] = [5, 33, 345, 45];
And furthermore, you can access the length of the second dimensions with:
int lengthOne = a[0].length;
int lengthTwo = a[1].length;
Is it logical? Absolutely. Jagged arrays are highly useful for things which don't fit the classic table format such as recording temperatures. This could be recorded as (for example):
double[][] temperatures = new double[12][];
Where there are 12 months in a year and:
temperatures[0] = new double[31];
January has 31 days.
Related
I've got to a dead end in the homework working on sorting a integers two-dimensional array.
The instructions are to create a function that takes a two-dimensional int array
(not necessarily a matrix) and sort the Outer array according to the sum of the inner arrays. in other words, in the first index of the array should be the inner array with the lowest sum.
Example -
input - int[][] array = {{2, 4, 1,9,9,9,9}, {6, 8}, {7, 3, 6, 5, 1}};
output - array = {{6, 8}, {7, 3, 6, 5, 1}, {2, 4, 1,9,9,9,9}};
My logic so far is creating a new one dimensional array that will include the sum
of each of the inner arrays from the main array.
and work with the sorting according to it.
public static int[] arraysCalculator(int[][] arr) {
int[] sums = new int[arr.length];
int sum= 0;
for(int i = 0; i < arr.length; i++)
{
for(int j = 0; j < arr[i].length; j++)
{
sum += arr[i][j];
}
sums[i] = sum;
sum = 0;
}
You can easily sum an int[] by streaming it and then calling sum(). From there, it's just a matter of calling Arrays.sort with a comparator that compares this sum:
Arrays.sort(array, Comparator.comparingInt(a -> Arrays.stream(a).sum()));
You got like one third. What you need now:
after creating that first array sums that contains the sums of the "inner" arrays, you simply create an exact copy of that array, like originalSums
then, you sort the content of sums
Example: say sums and originalSums are [ 12, 3, 7]. After sorting you get:
originalSums: [ 12, 3, 7]
sums: [ 3, 7, 12]
The thing is: by looking at both arrays, you can decide how to swap the inner arrays to match the order that sums shows you now.
In the above example, you notice that 12 has the original index 0. After sorting, its index is 2. So you know that you have to "swap" the inner arrays for 0 and 2. You can also deduce that 3 should go to index 0, and 7 to index 2.
Of course, it is still a bit of work to ensure that the swapping works out (like you better not swap any index twice).
The most basic way to get the whole thing going is to simply look at just one index at a time (like you do some sort of bubble sort).
Long story short: there are many different ways to solve this. I suggest you start with the easiest path.
In addition to the other answers who did a great job explaining the theory and laying the ground work for solving your assignment, here is a full working example (with detailed documentation on what each thing does and why) that will hopefully be of some assistance:
/**
* This method will sort the inner arrays of a given two dimensional array
* from lowest to highest value according to the sum of it's elements.
*/
private static int[][] arrayCalc(int[][] arr)
{
/*
* We're working with a TreeMap here because this type
* of map is allowed to have duplicate key entries
*/
java.util.Map<Integer, Integer[]> map = new java.util.TreeMap<>();
/*
* This value represents the largest inner array
* size found in 2d array passed as parameter
*/
int largestSize = 0;
for (int[] inner : arr) {
/*
* Convert the inner array to an array of Integer
* objects so it can be placed inside a map
*/
Integer[] integers = IntStream.of(inner).boxed().toArray(Integer[]::new);
map.put(IntStream.of(inner).sum(), integers);
/*
* Check if this inner array has a larger value
* then the largest array we processed so far
*/
if (inner.length > largestSize) {
largestSize = inner.length;
}
}
int[][] result = new int[map.size()][largestSize];
/*
* Iterate over the map and copy it's values which are represented
* as Integer arrays into inner arrays of our return value
*/
java.util.Iterator<java.util.Map.Entry<Integer, Integer[]>> iter = map.entrySet().iterator();
for (int i = 0; i < result.length && iter.hasNext(); i++)
{
java.util.Map.Entry<Integer, Integer[]> entry = iter.next();
/*
* We can just return our value as an array of Integer objects
* but for the sake of this exercise we will convert it to a
* primitive 2D int array so it's consistent with our method parameter
*/
Integer[] integers = entry.getValue();
result[i] = java.util.Arrays.stream(integers).mapToInt(Integer::intValue).toArray();
}
return result;
}
public static void main(String[] args)
{
int[][] array = {{2, 4, 1,9,9,9,9}, {6, 8}, {7, 3, 6, 5, 1}};
int[][] result = arrayCalc(array);
for (int[] iResult : result) {
System.out.println(Arrays.toString(iResult));
}
}
Output
[6, 8]
[7, 3, 6, 5, 1]
[2, 4, 1, 9, 9, 9, 9]
How could I set an int[] array to another int[]?
Example:
int array[] = new int{1, 2, 3, 4, 5};
int array2[] = new int[]array;
or
int array[] = new int{1, 2, 3, 4, 5};
int array2[] = array[];
But it doesn't work!
Can somebody tell me how?
Why didn't you try with the most obvious:
int[] array2 = array;
You can try to use
array2 = Arrays.copyOf(array, array.length);
From the Java docs:
copyOf
Copies the specified array, truncating or padding with zeros (if
necessary) so the copy has the specified length. For all indices that
are valid in both the original array and the copy, the two arrays will
contain identical values. For any indices that are valid in the copy
but not the original, the copy will contain 0. Such indices will exist
if and only if the specified length is greater than that of the
original array.
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);
}
I am trying to combine two arrays into one big array.
But I don't understand why it wont work.
Here's my code:
public class TestaCombine {
private int[] arrayX = new int[20];
private int[] arrayY = new int[6];
private int[] ratings;
public void getRanks(){
arrayX[0] = 3;
arrayX[1] = 4;
arrayX[2] = 2;
arrayX[3] = 6;
arrayX[4] = 2;
arrayX[5] = 5;
arrayY[0] = 9;
arrayY[1] = 7;
arrayY[2] = 5;
arrayY[3] = 10;
arrayY[4] = 6;
arrayY[5] = 8;
}
public void combine(){
ratings = new int[arrayX.length + arrayY.length];
System.arraycopy(arrayX, 0, ratings, 0, arrayX.length);
System.arraycopy(arrayY, 0, ratings, arrayX.length, arrayY.length);
Arrays.sort(ratings);
}
public void print(){
System.out.println(Arrays.toString(ratings));
}
public static void main(String[] args){
TestaCombine tc = new TestaCombine();
tc.getRanks();
tc.combine();
tc.print();
}
The output I am getting looks like this:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 10]
Don't understand where all the 0s comes from.
Note that the size of arrayX is 20. By default, ints have 0 value in Java. See the JLS - 4.12.5. Initial Values of Variables:
For type int, the default value is zero, that is, 0.
So when you do:
System.arraycopy(arrayX, 0, ratings, 0, arrayX.length);
It copies the zeros as well.
You're combining an array of size 6 with an array of size 20. The resulting array therefore has a size of 26.
But you've only specified 12 values, so the rest are filled in with values of 0. As you're sorting the collections, this also puts all the 0s at the start of the array.
It is because you have created one array with size of 20 and you only initialized 6 values within it, the rest of values where initialized during array initialization and they were all populated to 0's. When you combined array of size 20 and array of size 6 you received array of size 26 where 14 values are 0's
I would also like to recommend you apache commons libraries which contains nice set of tools for managing different collections.
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]);