How can I create an array with 40 elements, with random values from 0 to 39 ? Like
JavaScript
x
2
1
[4, 23, 7, 39, 19, 0, 9, 14, ]
2
I tried using solutions from here:
http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm
but the array I get is very little randomized. It generates a lot of blocks of successive numbers…
Advertisement
Answer
Here’s a solution that shuffles a list of unique numbers (no repeats, ever).
JavaScript
1
16
16
1
for (var a=[],i=0;i<40;++i) a[i]=i;
2
3
// http://stackoverflow.com/questions/962802#962890
4
function shuffle(array) {
5
var tmp, current, top = array.length;
6
if(top) while(--top) {
7
current = Math.floor(Math.random() * (top + 1));
8
tmp = array[current];
9
array[current] = array[top];
10
array[top] = tmp;
11
}
12
return array;
13
}
14
15
a = shuffle(a);
16
If you want to allow repeated values (which is not what the OP wanted) then look elsewhere. 🙂