Reputation: 35
let's assume that I have the next two dimensional int array:
int [][] mat = {{1 1 1 1 1},
{0 0 0 0 0},
{3 3 3 3 3},
{0 0 0 0 0},
{2 2 2 2 2}};
the reason i'm here is because I'm trying to think of a way to shuffle the rows in the next order (without losing the first row data):
first row data -> second row
second row data -> third row
third row data -> fourth row
fourth row data -> fifth row
a more detailed graphic explanation of what i've written:
original: 1 1 1 1 1 what i need: 1 1 1 1 1
0 0 0 0 0 1 1 1 1 1 <- first row data on the second row
3 3 3 3 3 0 0 0 0 0 <- second row data on the third row
0 0 0 0 0 3 3 3 3 3 <- third row data on the fourth row
2 2 2 2 2 0 0 0 0 0 <- fourth row data on the fifth row
meaning that the 1st row always remains constant
and that the original fifth row always loses its content
Any suggestion/tips of how I would implement such thing would be highly appreciated!
Upvotes: 1
Views: 189
Reputation: 2835
If you want to preserve row 0, you should loop from row 1 to the last row, setting the value of the previous row to the value of the current row.
Here's a simple, intuitive example which copies the values of every column of the array:
for (int i = 1; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
mat[i][j] = mat[i - 1][j]
}
}
Upvotes: 0
Reputation: 800
All you have to do here, is replace every row by its previous one. This can be easily achieved by looping through the columns with a reverse order, i.e your outer for loop will iterate backwards. Make sure to stop at the 2nd row (its index is 1 so that you maintain the original 1st row):
for (int i = mat.length-1; i>0; i--) {
// copy mat[i-1] into mat[i] for every element of this row
}
Upvotes: 1
Reputation: 646
you can easily use Arrays.CopyOf() and for each row copy the previous one
So, the code should be something like
public static void main (String[] args) throws java.lang.Exception
{
int [][] mat = new int[][]{{1,1,1,1,1},
{0, 0, 0 ,0 ,0},
{3, 3, 3, 3, 3},
{0, 0 ,0, 0, 0},
{2 ,2, 2 ,2 ,2}};
for(int i=mat.length-1;i>0;i--){
mat[i]=Arrays.copyOf(mat[i-1],mat[i-1].length);
}
// To check correctness
for(int i=0;i<mat.length;i++){
System.out.println(Arrays.toString(mat[i]));
}
}
Upvotes: 0
Reputation: 8215
Iterate backwards from the last row to the second one.
For each of these rows, assign the values from the previous row to it.
Upvotes: 1