Random Numbers

A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming.


Extract all of the numbers from an array in random order without repeating any of the numbers. The array consists of the numbers 0 through 9 so that in the original array the numbers appear in the corresponding numeric positions within the array.

Historical Answer:

var items = Array(0,1,2,3,4,5,6,7,8,9), a, i, n;
n = items.length;
while( n > 0 ) {
a = Math.floor( Math.random()* n );
for ( i = a; i <= n; ++i ) {
items[i] = items[i+1];

When I saw someone asking for help with this question they had used splice in their answer and the teacher had asked them to write it without using splice. In fact that was about the only modern JavaScript command they had actually used while just about everything else in the code was long obsolete.

Here the historical answer has been modified from what that person had used to only use the historical and obsolete commands that the teacher wanted.

JavaScript Answer:

<div id="items"></div>
Array.prototype.shuffle = function() {
var r=[],c = this.slice(0);
while (c.length) r.push(c.splice(Math.random() * c.length, 1));
return r;
Array.prototype.populate = function(n) {
return Object.keys(Object(0+Array(n)));
var x = [].populate(10);
document.getElementById('items').innerHTML = x.shuffle().join('');

Here we look at a more modern and also more flexible approach to the problem. This solution makes it easy to extend how many numbers we want randomly sorted (say 10000 instead of 10) and we can easily control how the resulting random numbers are used after being generated as they are not being output until after shuffling them.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow