Wednesday 24 August 2011

Programming Puzzles -Arrays




package com.test.progs;

/**
*
@author Thejas
*
*
* Given an unsorted array arr[] and two numbers x and y,
* find the minimum distance between x and y in arr[].
* The array might also contain duplicates.
* You may assume that both x and y are different and present in arr[].

Examples:
Input: arr[] = {1, 2}, x = 1, y = 2
Output: Minimum distance between 1 and 2 is 1.

Input: arr[] = {3, 4, 5}, x = 3, y = 5
Output: Minimum distance between 3 and 5 is 2.

Input: arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}, x = 3, y = 6
Output: Minimum distance between 3 and 6 is 4.

Input: arr[] = {2, 5, 3, 5, 4, 4, 2, 3}, x = 3, y = 2
Output: Minimum distance between 3 and 2 is 1.

*/

public class MinDist2num {

/**
*
@param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
//test Data
int array[] = {1,4,22,55,2,3,6,7,0,22,3,55,22,0,2,4,5,10,55,2,6,7};
int x=6,y=7;
int i=0,prev=-1,dist=10000;//set a high value for initial distance Dist

for(i=0;i<array.length;i++)
{
if(array[i]==x){
prev=i;
}else if(array[i]==y && prev!=-1){
dist=(i-prev)<dist?(i-prev):dist;
int temp=x;
x=y;
y=temp;
prev=i;
}else if(prev==-1 && array[i]==y)
{
int temp=x;
x=y;
y=temp;
prev=i;
}
}
System.out.println("the minimum distance between "+x+" "+y+" = "+dist);
return;
}

}
/****************************************************************************************
Solution:
Travrse array from 0th index note down the first occurance of either of the elements X or Y in a variable say PREV.
when first occurance of either is found swap X and Y such that found element is X and the other Y.
traverse array further if element at index is X update PREV with index else
if it is Y update variable DIST with distance of PREV and index if lesser than current value of DIST
and swap X and Y set PREV value to that of the index
******************************************************************************************/

No comments:

Post a Comment