GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  J2EE  >  Core Java

 Print  |  
Question:  Jumble Array Values

Answer: An array A is of size N. Write a java method that jumbles all values in the array. All possible permutations must be possible and chances for each possible permutation must be equal. For example, size of array A is 3. A[0]=x, A[1]=y, A[2] =z.
Possible permutations are 3! After jumbling elements, there would be equal chances for each of xyz,yxz,... to be in the array elements.


October 10, 2008 09:45:18 #2
 rjlast888   Member Since: October 2008    Total Comments: 1 

RE: Jumble Array Values
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


public class TestProgram
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {

        int n = 20;
        List a = new ArrayList(n);
        List randArray = new ArrayList(n);
        Map usedMap = new HashMap();
        
        for(int idx=0; idx < n; idx++)
        {
            a.add(new String(Integer.toString(idx)));
        }
        
        Random generator = new Random();
        for(int idx=0; idx < a.size(); idx++)
        {
            int position = getPosition(generator, usedMap, a.size());
            randArray.add(a.get(position));
        }
        
        for(int idx=0; idx < randArray.size(); idx++)
        {
            System.out.println((String)randArray.get(idx));
        }
        

    }

    private static int getPosition(Random generator, Map usedMap, int arraySize)
    {
        int pos = -1;
        
        while(pos == -1 && !usedMap.containsKey(pos))
        {
            float f = generator.nextFloat() * arraySize;
            int irand= (int)f;
            if(irand == arraySize)
            {
                irand--;
            }
            pos = irand;
        }
        
        usedMap.put(pos, null);
        
        return pos;
    }

}
     

 

Back To Question