I have a large array of arbitrary size. It's a square array. I'm trying to grasp how to traverse it diagonally like a /
rather than a \
(what I already know how to do). I have the following code thus far:
char[][] array = new char[500][500];
//array full of random letters
String arrayLine = "";
for (int y = 0; y < array.length; y++) {
for (int x = 0; x < array.length; x++) {
for (???) {
arrayLine = arrayLine + array[???][???];
}
}
System.out.println(arrayLine);
}
I have three loops, because this is how I did the other diagonal:
for (int y = 0; y < array.length; y++) {
for (int x = 0; x < array.length; x++) {
for (int z = 0; z < array.length-y-x; z++) {
arrayLine = arrayLine + array[y+z][x+z];
}
}
System.out.println(arrayLine);
}
In my attempts, I keep going outside the boundaries and get an ElementOutOfBounds exception. Say the array is as below (a 3x3 instead of 500x500):
A B C
D E F
G H I
I want to print out the following as strings:
A
BD
CEG
FH
I
A previous SO question had a similar problem with integer arrays, and the solution is based off of the sum of array elements. But I'm working with chars, so I can't think of a methodology to get it.
i
andj
for each point in the array. You'll notice that B,(0, 1)
and D,(1, 0)
both sum to 1. Consider this application when figuring this out. Note: it is also important to check bounds.i and j
I referred to the coordinates. C, E and G would have a value of 2. F and H would have a value of 3. I's value is 4.