I am completing the CodingBat exercises for Java. Here is the one I have completed just now:
Given
n > = 0
, create an array lengthn * n
with the following pattern, shown here forn = 3
:
{0, 0, 1, 0, 2, 1, 3, 2, 1}
(spaces added to show the 3 groups).
Here is my code:
public int[] squareUp(int n){
int[] ary = new int[n * n];
int numberToInsert = 1;
int count = 0;
int target = n;
//Guard condition for n = 1
if (n == 1) {
ary[0] = 1;
return ary;
}
//Do the following n times
for (int i = 0; i < n; i++) {
//Working from the end of the array backwards, insert the number
//at the appropriate point
for (int j = ary.length - numberToInsert; j > 0; j -= n) {
ary[j] = numberToInsert;
//The amount of times a number is inserted decreases each
//iteration
count++;
if (count == target) {
count = 0;
target--;
break;
}
}
numberToInsert++;
}
return ary;
}
My questions are:
- How would I implement this without the guard condition? The result without it is
0
because it doesn't get as far as the secondfor
loop, asnumberToInsert
is already1
. I tried to set this as0
, and increment it later in the code, but I couldn't figure this out. - What alternative is there to the
count
andtarget
system I implemented? Was this a good or bad way to achieve the outcome? - How else could the numbers be inserted? The method I used felt the most logical but I'm curious to see other methods.