Thursday, March 3, 2011

Given Arrays as If [a1,a2,a3...,an,b1,b2...bn] is given input change this to [a1,b1,a2,b2.....an,bn]

#include

void print_arr(int* arr, int len)
{
int i;
printf("\n Array is \n");
for (i = 0; i < len; i++)
{
printf("%d ", arr[i]);
}
printf("\n");

}

int get_right_index(int i, int len)
{
if (i < len/2) {
return 2*i;
}
return 2*(i-len/2)+1;

}

int get_right_candidate(int i, int len)
{
if (i%2) {
return (i-1)/2 + len/2;
}
return i/2;

}

void make_pattern(int* arr, int len)
{
if (len%2) {
return;
}

if (len == 2)
{
return;
}

int total_no_assign = 0;
int index = 1;

while (total_no_assign < (len -2)) {
int cur = index;
int val = arr[cur];
int target_index = get_right_index(cur, len);

if (val < 0) {
printf("\n Already shuffled");
index++;
continue;
}

while(cur != target_index) {
int ci = get_right_candidate(cur, len);
arr[cur] = 0 - arr[ci];
printf("\n Index shuffled cur = %d, ci = %d\n", cur, ci);
cur = ci;
total_no_assign++;
print_arr(arr, len);
}

arr[cur] = 0 - val;
total_no_assign++;
print_arr(arr, len);
}

int i;
for (i = 0; i < len; i++) {
if (arr[i] < 0) {
arr[i] = 0 - arr[i];
}
}

}

int main()
{
int arr[]={1,2,3,4,5,6,7,8};

int count=sizeof(arr)/sizeof(int);
if (count%2) {
return -1;
}




print_arr(arr, count);

make_pattern(arr, count);
print_arr(arr, count);

return 0;

}

No comments :