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;
-
\$\begingroup\$ Can you give more details on what is expected? Another example or an explanation would be much appreciated. \$\endgroup\$SylvainD– SylvainD2013年09月24日 22:56:30 +00:00Commented Sep 24, 2013 at 22:56
-
\$\begingroup\$ @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. \$\endgroup\$Old Badman Grey– Old Badman Grey2013年09月25日 02:57:06 +00:00Commented Sep 25, 2013 at 2:57
1 Answer 1
I do prefer the solution with the boolean. Also, a third possible variant would be to fill every other from left to right and remaining rows from right to left
In any case, they way you are supposed to handle arrays where size is not A*B might help you to pick the best solution for you.
-
\$\begingroup\$ So you prefer the readability of the method with the boolean and to determine the most efficient method I could just time them? \$\endgroup\$Old Badman Grey– Old Badman Grey2013年10月30日 01:45:23 +00:00Commented Oct 30, 2013 at 1:45