This multidimensional array of displayed in Schildt' book, 9th edition.
I do not understand how the output, except for the 0, 1, 2, 3, 4.
Can you explain how the other for loop works?
I understand that 4 and 5 are the number of rows and columns, but I do not comprehend the values: 15, 16, 17, 18, 19.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
The loops are executed and k is incremented for total 4*5 = 20 times. Here is how the program is executed
for(i=0; i<4; i++) // Run outer loop 4 times
for(j=0; j<5; j++) { // For every outer loop iteration, run inner loop 5 times
twoD[i][j] = k;
k++; // for every inner loop iteration, increment k by 1
}
Related
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);
}
}
}
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
The easy solution here is to use an ArrayList, however, we can also create variable length rows using the following, note the comments below explaining the process, but the key is this int[][] evenMatrix = new int[n][];, note how we only specify the column size, not the row size.
Complete code:
System.out.println("***** EvenMatrix *****");
//Create 3D array
int[][] evenMatrix = new int[n][];
for (int i = 0; i < arr.length; i++) {
//Create inner row that we will trim later
int[] evenElements = new int[m];
//Create a counter to track variable locations
int counter = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else{
evenElements[counter] = arr[i][j];
//Incriment counter
counter++;
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
//Trim the inner array to the correct length that we know from the `counter`
evenElements = Arrays.copyOf(evenElements, counter);
//Assign the inner row of variable length to the 3D matrix
evenMatrix[i] = evenElements;
}
//Print the result
System.out.println(Arrays.deepToString(evenMatrix));
Example output of the above code:
1 11 15 0 15 18 10
6 12 0 13 15 15 3
10 13 6 1 12 4 12
10 7 12 8 19 4 6
5 10 4 12 4 5 5
***** EvenMatrix *****
0 18 10
6 12 0
10 6 12 4 12
10 12 8 4 6
10 4 12 4
[[0, 18, 10], [6, 12, 0], [10, 6, 12, 4, 12], [10, 12, 8, 4, 6], [10, 4, 12, 4]]
(link: https://www.interviewbit.com/problems/array_2d/)
having difficulty in performing a dry run for the following code with performOps being called with
A : [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] .
ArrayList<ArrayList<Integer>> performOps(ArrayList<ArrayList<Integer>> A) {
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>();
for (int i = 0; i < A.size(); i++) {
B.add(new ArrayList<Integer>());
for (int j = 0; j < A.get(i).size(); j++) {
B.get(i).add(0);
}
for (int j = 0; j < A.get(i).size(); j++) {
B.get(i).set(A.get(i).size() - 1 - j, A.get(i).get(j));
}
}
return B;
}
Can anyone please help me in understanding it?
The output will be
4 3 2 1
8 7 6 5
12 11 10 9
You must be trying to initialize A.That is not the case here.The value of A is
1 2 3 4
5 6 7 8
9 10 11 12
and then the output of the further code is asked in the question.Please read the question carefully.Reach out if you need anything else.Cheers
Try substituting the variable values for one or two loops. That will be easier to understand such questions and if possible code it in editor and debug through the code one step at a time.
I have tried for one loop.
ArrayList<ArrayList<Integer>> performOps(ArrayList<ArrayList<Integer>> A) {
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
//A.size() is 3
for (int i = 0; i < 3; i++) {
B.add(new ArrayList<Integer>());
//First Loop i = 0; A.get(0).size() = 4; Four elements in first index of array list
for (int j = 0; j < 4; j++) {
B.get(0).add(0); //Setting all elements to zeros
}
for (int j = 0; j < 4; j++) {
B.get(0).set(4 - 1 - j, A.get(0).get(j));
//For j = 0
// B.get(0).set(3, 1); //A.get(0).get(0) = 1
//For j = 1
B.get(0).set(2, 2); //A.get(0).get(1) = 2
//For j = 2
B.get(0).set(1, 3); // A.get(0).get(2) = 3
//For j = 3
B.get(0).set(0, 4); //A.get(0).get(3) = 4
}
//At the end of above loop B=[[4, 3, 2 ,1]]
}
return B;
}
By the way the output will be two dimensional collection with each inner collection elements in reverse order.
I am trying to solve a problem on multi dimensional array using Java. I need to print all the numbers appearing diagonally for a given two dimensional matrix. I have done for one scenario but not able to do for the rest of the elements
public class TwoDimensionalArray {
private static int[][] array = {{1,2,3,4},{5,6,7,8},{9,10,11,12,}, {13,14,15,16}};
public static void main(String args[]){
for (int i=0;i<4; i++){
for(int j=0;j < 4; j++){
System.out.print(" "+ array[i][j] +" ");
}
System.out.println();
}
System.out.println();
for (int i = 0;i < 4; i++){
int offset = 0;
for(int j = offset;j <= i; j++){
System.out.print("i >> "+i+" ");
System.out.print("j >> "+j);
System.out.println(" == "+ array[i][i+offset] +" ");
}
offset++;
}
}
}
I started off writing the below code to get the first diagonal elements printed correctly.
for (int i = 0;i < 4; i++){
int offset = 0;
System.out.print(array[i][i+offset] +" ");
offset++;
}
Output: 1 6 11 16
But when I try to extend the same approach by adding inner for loop, I start iterating from 0 till i every time which results it printing the elements more than one time and not with correct output. Is my approach right or I am missing something when implementing the inner for loop.
The desired output should be like below:
1 6 11 16
2 7 12
3 8
4
5 10 15
6 11 16
7 12
8
9 14
10 15
11 16
12
This is not an assignment. I am just trying to improve my programming skills. Also please let me know the difficulty level of this problem on a scale of 1 to 5, 5 being hardest and 1 being simple.
I suppose you're looking for something like this:
private static int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12,}, {13, 14, 15, 16}};
private static void f(int y, int x) {
while ((y < 4) && (x < 4))
System.out.print(array[y++][x++] + " ");
System.out.println();
}
public static void main(final String args[]) {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
f(i, j);
}
public class testing
{
public void show() {
int num = 0;
int n = 5;
for (int i=1; i<n; i++) {
for (int j=0; j<i; j++) {
System.out.print(num++);
System.out.print(" ");
}
System.out.println(" ");
}
}
}
This question came up in one of our previous exams and I don't understand it. The answer is
0
1 2
3 4 5
6 7 8 9
But I have no clue how they got it. I kind of understand the 2nd to 4th line but have no clue how they got 0 on the first line. Any explanation would be highly appreciated, thanks!
but have no clue how they got 0 on the first line ?
int num = 0; --> it is 0 initially
For the first iteration your inner loop executes only 1 time
for (int i=1; i<n; i++) {
for (int j=0; j<i; j++) { ---> for(int j=0;j<1;j++) // for 1st time
So that is why the below line
System.out.print(num++); //printed 0
Note : there is a tool known as debugger , Use it !!
Maybe the following amended code could help to understand
int num = 0;
int n = 5;
for (int i=1; i<n; i++) { // loop from 0 to 4
System.out.printf("num=%d i=%d : ", num, i);
for (int j=0; j<i; j++) { // loop from 0 to i
System.out.print(num++); // print num then increment num
System.out.print(" ");
}
System.out.println(" ");
}
output
num=0 i=1 : 0
num=1 i=2 : 1 2
num=3 i=3 : 3 4 5
num=6 i=4 : 6 7 8 9
I believe your problem lies in this line
System.out.print(num++);
in a more verbose way it does the following
System.out.print(num);
num = num + 1;
i need some help writing a for-loop please but i can't get it.
i need to add the numbers 0 to 63 in a table like this:
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
etc.
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
table.setValueAt(""+(i+(j)), i, j);
}
}
but the inputted values are not correct
can you please help
(Assuming you're trying to do this so you count left to right top to bottom and have 8 columns)
You need to offset the value each time for the number of columns you've seen. Every time you iterate through an entire row, you've seen 8 columns, so it's not sufficient to add i and j, you need to add rows seen (i) multiplied by the number of columns (8). Thus you should be printing i*8 + j:
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
table.setValueAt(""+(i*8+j), i, j);
}
}