Skip to content

Instantly share code, notes, and snippets.

@m-Py
Created June 2, 2016 10:02
Show Gist options
  • Select an option

  • Save m-Py/744f439ab127f118ed15ab602ce49ede to your computer and use it in GitHub Desktop.

Select an option

Save m-Py/744f439ab127f118ed15ab602ce49ede to your computer and use it in GitHub Desktop.
Generate an array of any length n returning an array that contains a random sequence with integers 0 to n-1
rndSequence = function(length) {
options = length;
option_sequence = [];
for (var i = 0; i < options; i++) {
if (option_sequence.length === 0) {
var rnd = Math.floor(Math.random()*options);
option_sequence.push(rnd);
}
else if (option_sequence.length > 0) {
var rnd = Math.floor(Math.random()*options);
while (option_sequence.indexOf(rnd) != -1) {
var rnd = Math.floor(Math.random()*options);
}
option_sequence.push(rnd);
}
}
return option_sequence;
}
@m-Py
Copy link
Copy Markdown
Author

m-Py commented Jun 2, 2016

Usage:
console.log(rndSequence(5)) // random sequence of length 5

[1,3,2,4,0] // e.g.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment