Flip an array on its head?
Ok, did my researching and haven't found anything.
In Java, a 2D array usually prints down and then left (or left then down depending on how you word your for loops). But how can I take that same array, and print it left and up? I don't want t开发者_开发百科o flip the array itself because I plan to add on to it (So say, instead of having 18 rows, have idk, 30 mid-game).
So my question is: how can you print a 2D array in Java from bottom, up?
Start from the end:
for (int i = arr.length - 1; i >=0; --i) {
for (int j = arr[i].length -1; j >= 0; --j) {
System.out.println(arr[i][j]);
}
}
Although the other answers are easier and more terse, if you do this often, you could alternately write an Iterator that would traverse the array in reverse order:
public class ReverseArrayIterator<T> implements Iterator<T> {
private final T[] myArray;
private int pointer;
public ReverseArrayIterator(T... myArray) {
this.myArray = myArray;
pointer = myArray.length;
}
@Override
public boolean hasNext() {
return pointer > 0;
}
@Override
public T next() {
if (!hasNext())
throw new NoSuchElementException();
return myArray[--pointer];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
If you mean that "down and left" is this:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
then "bottom up" would be something like this:
for (int i = arr.length-1; i >= 0; i--) {
for (int j = arr[i].length-1; j >= 0; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
... Reverse the indices in the for loop ...
Or, if you're using the new fast enum for loop, switch to indices.
Or, index by array.length - i - 1
精彩评论