Thursday, 8 August 2013

Interchangeable Height


There are n persons which are standing in a row. If ith person’s height is greater than jth person’s height (i < j in the row) then pair of these two persons is said to be interchangeable.
So you have to find out the number of pairs that are interchangeable.

Assume that height is in format x’y’’ (i.e. x ft and y inches).

Consider an example of four persons standing in a row. Let 1st person has height 5’8’’, 2nd has height 5’7’’, 3rd has height 6’0’’ and 4th has height 5’7’’. You can see that 1st person and 2nd person are interchangeable, 1st person and 4th person are interchangeable, 3rd person and 4th person are interchangeable. So there are 3 pairs which are interchangeable. So output should be 3 here.

Solution:


class FindInterchangableHeights{
        static int findSwaps(String []arr){
if(arr == null || arr.length == 0)
return -1;

int swap = 0;  //Hold the count of interchangeable heights
                String []height;
 
for(int i = 0; i < arr.length; i++){
height = arr[i].split("#");
int x = Integer.valueOf(height[0]);
int y = Integer.valueOf(height[1]);
if(!validate(x, y))
return -1;

for(int j = i+1; j < arr.length; j++){
height = arr[j].split("#");
int x1 = Integer.valueOf(height[0]);
int y1 = Integer.valueOf(height[1]);
if(!validate(x1, y1))
return -1;

if(x*12+y > x1*12+y1)
swap++;
}
}
return swap;
}

        /*utility to validate the height*/
static boolean validate(int x, int y){
if( x<4 || x>7 || y<0 || y>11)
return false;
return true;
}

public static void main(String... args){
String []height = {"5#9","5#7"};
int swap = find(height);
System.out.println(swap);
}
}

No comments:

Post a Comment