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.
Total Answers and Comments: 7
Last Update: August 13, 2009 Asked by: venkatalaks
public class Test { public static void main(String[] args) { HashMap hm = new HashMap(); int arr[] = new int[20]; for (int i = 0 ;i<20; i++) { arr[i]=i; hm.put(String.valueOf(new Random().nextInt()),String.valueOf(i)); } Collection arr1 = hm.values(); Iterator i = arr1.iterator(); while (i.hasNext()) { System.out.println((String)i.next()+" "); } } }
Random generator new Random(); for(int idx 0; idx < a.size(); idx++) { int position getPosition(generator usedMap a.size()); randArray.add(a.get(position)); }
public class Test { public static void main(String[] args) { HashMap hm new HashMap(); int arr[] new int[20]; for (int i 0 ;i<20; i++) { arr[i] i; hm.put(String.valueOf(new Random().nextInt()) String.valueOf(i)); } Collection arr1 hm.values(); Iterator i arr1.iterator(); while (i.hasNext()) { System.out.println((String)i.next()+" "); } } }
void jumble(Object[] A) { Random rand new Random(System.currentTimeMillis()); Object temp; for (int i 0; i < A.length; i++) { int idx rand.nextInt(A.length); temp A[idx]; A[idx] A[i]; A[i] temp; } }
} // print it out again just to show it shuffles up the arrays contents System.out.println("n--------------"); Collections.shuffle(mylist); for(int j 0; j<20; j++) { System.out.print(mylist.get(j)+" ");