Hey guys i am trying to shuffle and array of integers. Lets say i have this array: int[] array={1,2,3,4,5}; I want to shuffle it so the order becomes completely random. For example: int[] array={3,5,1,4,2}; for java
Asked
Active
Viewed 962 times
-3
-
Programming language is? Your "trying" code is? – Hardy Dec 14 '13 at 23:23
3 Answers
2
Not sure what programming language you are using but I'll answer it in Python.
from random import shuffle
alist = [[i] for i in range(5)]
shuffle(alist)

kiasy
- 304
- 3
- 6
- 17
1
The algorithm to shuffle is quite simple - but you need to get it exactly right or the shuffle isnt actually random.
In java:
for (int i=0;i<arr.length;i++) {
int swap = random.nextInt(arr.length-i) + i;
int temp = arr[swap];
arr[swap] = arr[i];
arr[i]=temp;
}
Basically you scan through the list swapping the current element in the list with one picked at random from itself to the end of the list.
It is important that you only pick forwards as otherwise you do not end up with an even distribution.
Most languages (Java included) have a shuffle function built in though.

Tim B
- 40,716
- 16
- 83
- 128
0
I will answer in Java:
int[] a = int[] { 1, 2, 3, 4, 5 }; // example array
int length = a.length(); // for convenience, store the length of the array
Random random1 = new Random(); // use a standard Java random number generator
int swap = 0; // use an extra variable for storing the swap element
int r1 = 0; // for convenience, store the current randomly generated number
for (int i=0; i<length(); i++) { // iterate over each field of the array
r1 = random1.nextInt(length - 1); // generate a random number representing an index within the range of 0 - a.length - 1, i.e. the first and the last index of the array
swap = a[i]; // swap part 1
a[i] = a[r1]; // swap part 2
a[r1] = swap; // swap part 3
}
// that's it, array is shuffeld according to the Java random generator

marc wellman
- 5,808
- 5
- 32
- 59