Tuesday 20 August 2013

Rearrange an array using swap with 0

You have two arrays src, tgt, containing two permutations of the numbers 0..n-1. You would like to rearrange src so that it equals tgt.

The only allowed operations is “swap a number with 0”, e.g. {1,0,2,3} -> {1,3,2,0} (“swap 3 with 0”). Write a program that prints to stdout the list of required operations.

Solution:

class RearrangeArrayUsingSwapWithZero{
static void arrange(int []src, int []target){
if(src == null || target == null)
return;

for(int i = 0; i < src.length; i++){
if(src[i] != target[i] && target[i] != 0){
int indexOfZero = findIndex(src, 0);
swap(src, indexOfZero, i);
int idx = findIndex(src, target[i]);
swap(src, i, idx);
System.out.println("swap "+target[i] +"with 0");
}
}
}

/*function to find the index of given number in the array*/
static int findIndex(int[]arr, int n){
for(int i = 0; i < arr.length; i++){
if(arr[i] == n)
return i;
}
return -1;
}

/*Utility function to swap array elements*/
static void swap(int []arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

public static void main(String... args){
                /*Test Case - 1*/
int []src = {1,0,2,3};
int []target = {1,3,2,0};
arrange(src, target);

                /*Test Case - 2*/
int []src1 = {1,0,2,3};
                int []target1 = {0,2,3,1};
arrange(src1, target1);
}
  }

1 comment:

  1. I don't able to understand question. Can u plz elaborate little more

    ReplyDelete