Social Icons

Wednesday, March 31, 2010

SquareUp- Solutions for Javabat Questions 1


This is my first attempt to provide solutions for Questions in Javabat , For the first one i chose an Array Question : here it its
Original Question:
Given n , create an array length n*n with the following pattern, shown here for n=3 : {0, 0, 1,  0, 2, 1,  3, 2, 1} (spaces added to show the 3 groups).

squareUp(3) → {0, 0, 1, 0, 2, 1, 3, 2, 1}
squareUp(2) → {0, 1, 2, 1}
squareUp(4) → {0, 0, 0, 1, 0, 0, 2, 1, 0, 3, 2, 1, 4, 3, 2, 1}


Source

You see the pattern of this right  1 comes always at an index where it index%n==0 , what we must do is divide the process into two ,, first filling up the main array and the pattern within , we can consider it as also an virtual array or something..
e-g for the squareUp(3) patterns are
001 , 021 , 321


public int[] squareUp(int n) { 
   int[] x=new int[n*n];
   for(int i=1; i<=n ; i++){
     for(int j=1; j<=i; j++ )
         x[(i*n)-j]=j;  
}
   return x;
}

Comments (3)

Loading... Logging you in...
  • Logged in as
I know this is years old, but thank you! I am just learning to code and i find your solution much more understandable than others that I could find.
1 reply · active 566 weeks ago
Awesome bro, glad someone found it usefull. :)
public int[] squareUp(int n) {
int[] kvad = new int[n*n];
for (int i=1; i<n+1; i++) {
for (int j = 0; j < n; j++){
if (i+j <n) {
kvad[(i-1)*n +j] = 0;
}
if (i+j == n) {
kvad[(i-1)*n+j] = i;
}
if (i+j > n) {
int k = i + j -n;
kvad[(i-1)*n +j] = i-k;
}
}
}
return kvad;
}

Post a new comment

Comments by

 
 
Blogger Templates http://slots.to/