# Switching directions in iterating 2D arrays

I had to do this in a course a while back: make {1,2,3,4,5,6,7,8,9} into {{1,2,3},{6,5,4},{7,8,9}}. When doing it, I just made the inner for-loop do all the work. But most of my friends had a Boolean and an if-statement to chose between a forward or reverse loop.

Which is more optimal and which is more readable?

private double[][] a;
public TwoD(int numRows, int numCols, double[] oneD){
a = new double[numCols][numRows];
int d =1;
int x = 0;
int i = 0;
for (int y=0; y<numCols; y++){
for (;x<numRows&&x>=0;x+=d){
a[y][x] = oneD[i];
i++;
}
d*=-1;
x+=d;
}
}


Edit: I had to have an object with a constructor which took width and height and a one dimensional array. The 1d array would be put into a 2d array as if it was a physical string being laid out (→▬▬↓←▬▬↓→▬▬).3x3 is an easy example.
1 3 9 5 4 7 3 1 5 to
1 3 9→
7 4 5←
3 1 5→

The alternative would be like (is pseudo code ok when its not the code being reviewed?)

boolean right = true;
for y
if right
for x++
else
for x--
right= !right;

• Can you give more details on what is expected? Another example or an explanation would be much appreciated. – SylvainD Sep 24 '13 at 22:56
• @Josay this was actually part of a written test I took last year and wasn't sure if I could just ask this but the questions are publicly available online and this is taken out of its original context (it was not explained with a string) so I think its fine. I want my unique answer analyzed to see if it is better or if it can be better. The, also public, answer key just wanted does the code you wrote down get the job done. – Old Badman Grey Sep 25 '13 at 2:57