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.


September 09, 2008 13:29:57 #1
 vinshv   Member Since: September 2008    Total Comments: 1 

RE: Jumble Array Values
 

public class Main {
    static String[] A = new String[] {"1", "2", "3", "4"};
  
    private static String toString(String[] s) {
        String result = "";
        for (int k=0; k < s.length; k++) {
            result += s[k];
        }
        return result;
    }

    private static void swap(int i, int j) {
        String tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }

    public static void main(String[] args) {
        int i, j;
 
        System.out.println(toString(A));

        for (i = 0; i < A.length; i++ ) {
            for (j = i+1; j < A.length; j++) {
                swap(i, j);
                System.out.println(toString(A));
            }
        }
    }
}

     

 

Back To Question