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;
}

 
 
Blogger Templates http://slots.to/