-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;
        }
    }
4
  • 1
    What's the problem? Where is your swap method? Commented Feb 12, 2013 at 5:14
  • 1
    What happened to the j>=i requirement? Commented Feb 12, 2013 at 5:14
  • In any case, why shuffle when you can SHUFFLE: see stackoverflow.com/questions/8116872/… Commented Feb 12, 2013 at 5:15
  • I don't know what would be the code for that. Commented Feb 12, 2013 at 5:16

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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]

3 Comments

Where I can find java.util.Collections.shuffle ? I can't see it in java API.
@user1995200 look for Collections class and shuffle is a static method in it
I can see that but there is no code here, it just explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.