I have 5 object, the order that they are shown should be random, to do this I have decided to to create an array which will have a sequence of numbers which represents the order to visit the objects (This will be stored in the users cookie). How do I go about creating a random sequence of non-recurring numbers from 0 to 4 (array starts at 0)?
Asked
Active
Viewed 29 times
0
-
1Can you post the code you've attempted so far? – Tom O. Feb 12 '19 at 16:33
-
Better approach is to create an array filled with 0 through 4 then randomly shuffle the array. See https://stackoverflow.com/a/2450976/1715579 – p.s.w.g Feb 12 '19 at 16:34
1 Answers
0
you can write a dummy shuffle algorithm
const arr = [0,1,2,3,4];
const limit = 10;
var i = 0;
while(i++ < limit) {
const a = Math.floor(Math.random() * 5)
const b = Math.floor(Math.random( ) * 5)
if( a !== b){
// swap arr[a] and arr[b]
var temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
basically for some iterations you can swap any two random indices in your array

ashish singh
- 6,526
- 2
- 15
- 35