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;