Total Pageviews

Wednesday, May 30, 2012

Amazon online test question.

In given array of elements like [a1,a2,a3,..an,b1,b2,b3,..bn,c1,c2,c3,...cn] Write a program to merge them like [a1,b1,c1,a2,b2,c2,...an,bn,cn].

PS: Do it without using extra memory
Sample Testcases:
Input #00:
{1,2,3,4,5,6,7,8,9,10,11,12}
Output #00:
{1,5,9,2,6,10,3,7,11,4,8,12}
Explanation:
Here as you can notice, the array is of the form
{a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4}
 Solution:
Transpose of matrix.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
i: 0; new_idx: 0
i: 1; new_idx: 8
i: 2; new_idx: 16
i: 3; new_idx: 8
i: 4; new_idx: 9
i: 5; new_idx: 17
i: 6; new_idx: 16
i: 7; new_idx: 10
i: 8; new_idx: 18
i: 9; new_idx: 18
i: 10; new_idx: 11
i: 11; new_idx: 19
i: 12; new_idx: 18
i: 13; new_idx: 18
i: 14; new_idx: 20
i: 15; new_idx: 17
i: 16; new_idx: 18
i: 17; new_idx: 21
i: 18; new_idx: 18
i: 19; new_idx: 20
i: 20; new_idx: 22
i: 21; new_idx: 22
i: 22; new_idx: 22
i: 23; new_idx: 23
1 9 17 2 10 18 3 11 19 4 12 20 5 13 21 6 14 22 7 15 23 8 16 24






--
Thanks & Regards
Manish Kumar


6 comments:

  1. Could you please post the sample code?

    ReplyDelete
    Replies

    1. #include
      using namespace std;
      int getIndex(int idx, int N) {
      return (idx % 3) * N + (idx / 3);
      }

      void swap(int *x, int *y) {
      if (x != y) {
      *x ^= *y;
      *y ^= *x;
      *x ^= *y;
      }
      }

      void orderArray(int a[], int len) {
      int N = len / 3;
      for(int i = 0; i < len; i++) {
      int idx = getIndex(i, N);
      while(idx < i) {
      idx = getIndex(idx, N);
      }
      printf("i: %d; new_idx: %d\n", i, idx);
      swap(a[i], a[idx]);
      }
      }

      int main () {
      int len = 24;
      int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
      for(int i = 0; i < len; i++) {
      printf("%d ", a[i]);
      }
      printf("\n");
      orderArray(a, len);
      for(int i = 0; i < len; i++) {
      printf("%d ", a[i]);
      }
      printf("\n");
      return 0;
      }

      Delete
    2. public static int[] mergeArray(int[] inputArray, int totalUnits) {
      int[] outputArray = new int[inputArray.length];
      int unitLength = inputArray.length/totalUnits;
      int k=0;
      for(int i=0; i<unitLength ; i++) {
      for(int j=0; j<totalUnits; j++)
      outputArray[k++] = inputArray[i+j*unitLength];
      }
      return outputArray;
      }

      Delete
  2. int idx = getIndex(i, N);
    while(idx < i) {
    idx = getIndex(idx, N);

    not clear :(

    ReplyDelete
  3. for(int i=0;i<a.length/3;i++)
    {
    int j= a.length/3;
    System.out.print("--- "+a[i]+" ---"+a[i+j]+"--- "+a[i+ 2*j]);
    }

    ReplyDelete