My Java code get all numbers I need, but every row in new array have length like in old array. How to make array with different row length only for numbers I've got?
Please check for my code:
import java.util.Arrays;
import java.util.Random;
public class Help {
public static void main(String[] args) {
Random random = new Random();
int n = random.nextInt(10);
int m = random.nextInt(10);
if (n > 0 && m > 0) {
int[][] arr = new int[n][m];
for (int i = 0; i < arr.length; i ) {
for (int j = 0; j < arr[i].length; j ) {
arr[i][j] = random.nextInt(20);
System.out.print(arr[i][j] " ");
}
System.out.println();
}
System.out.println();
System.out.println("***** EvenMatrix *****");
int[][] evenMatrix = new int[n][m];
int evenElement = 0;
for (int i = 0; i < arr.length; i ) {
for (int j = 0; j < arr[i].length; j ) {
if (arr[i][j] % 2 != 0) {
continue;
} else
evenElement = arr[i][j];
for (int k = 0; k < arr[i].length; k ) {
evenMatrix[i][j] = evenElement;
}
System.out.print(evenMatrix[i][j] " ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix));
} else {
System.out.println("Incorrect array length! Try again!");
System.exit(0);
}
}
}
CodePudding user response:
I wanted to help but didn't understand the question well Let's say your random numbers are 3x3 for n and m
And let's say your array "arr" is
[1,2,3]
[4,5,6]
[7,8,9}
And you want to be your array "evenMatrix" to be
[2,4,6,8] n = 1 and m = 4
or
[2,4] n = 2 and m = 2
[6,8]
Not n = 3 m = 3 just like in the array "arr"
[2,4,6]
[8,0,0]
is that right? If so you can check n and m before creating the "evenArray" like
int[][] evenMatrix;
if(n<m)
evenMatrix = new int[m][m];
else
evenMatrix = new int[n][n];
creating a square matrix but this still has problems let's say your random numbers are n = 5 and m = 2 so this code will create a 5x5 matrix and fill with even numbers and let's say your randomize arr array doesn't have that many even numbers are so it will become something ugly
CodePudding user response:
The easy solution here is to use an ArrayList
, we can easily convert it, note the comments below:
System.out.println("***** EvenMatrix *****");
//Create an ArrayList
ArrayList<ArrayList<Integer>> evenMatrix = new ArrayList<>();
for (int i = 0; i < arr.length; i ) {
//Rather than adding single items, instead create one row at a time
ArrayList<Integer> evenElementRow = new ArrayList<>();
for (int j = 0; j < arr[i].length; j ) {
if (arr[i][j] % 2 != 0) {
continue;
} else
//Add each even number to the evenElementRow
evenElementRow.add(arr[i][j]);
System.out.print(arr[i][j] " ");
}
//Finally at the end of each row we add the complete row to the 3D ArrayList
evenMatrix.add(evenElementRow);
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix.toArray()));
Example output:
19 6 10 19
16 18 19 16
13 13 8 10
8 0 3 10
14 5 13 3
***** EvenMatrix *****
6 10
16 18 16
8 10
8 0 10
14
[[6, 10], [16, 18, 16], [8, 10], [8, 0, 10], [14]]