-2

I wrote codes for the following question but they don't work. I get random numbers but the shuffle method don't shuffle them. Would you please help me?

for( each index i)

   choose a random index j where j>=i.
   swap the elements at index i and j.

My code is:

public static void shuffle(int[] a){
   for( int i = 0; i < a.length-1; i++){
       int range = a.length; 
       int j = (int) (Math.random() * range);
       swap(a, i, j);      
  }
}

public static void swap(int[] array, int i, int j){

        if (i != j) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525

2 Answers2

0

There is java.util.Collections.shuffle which works with List. I suggest to copy-paste the algorithm from src and change it to work with int[]:

public static void shuffle(int[] a) {
    Random rnd = new Random();
    for (int i = a.length; i > 1; i--) {
        swap(a, i - 1, rnd.nextInt(i));
    }
}

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


public static void main(String[] args) {
    int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    shuffle(a);
    System.out.println(Arrays.toString(a));
}

prints

[8, 7, 3, 4, 6, 1, 2, 5, 9]
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Convert your array to Integer Wrapper class and call the Collections.shuffle by converting Integer array to List. The snippet is below

you should have access to the Apache lang library, then you can use the ArrayUtils.toObject(int[]) method like this:

int [] array = {1,2,3,4,5,6};
Integer[] newArray = ArrayUtils.toObject(array);
Collections.shuffle(Arrays.asList(newArray));
for (int i = 0; i < newArray.length; i++) {
    System.out.println(newArray[i]);
}

If you donot have the Apcahe Lang Library, then you can do this way

Integer[] newArray = new Integer[array.length];
int i = 0;
for (int value : array) {
    newArray[i++] = Integer.valueOf(value);
}
Srikanth Sridhar
  • 2,317
  • 7
  • 30
  • 50