Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialColton Fitzgerald
15,815 PointsHow to randomize the order that functions are run?
I know there is a better way to do this. Any ideas?
randomRadio = Math.round(Math.random() * 4);
if (randomRadio === 4) {
createRadios("d");
createRadios("c");
createRadios("b");
createRadios("a");
} else if (randomRadio === 3) {
createRadios("c");
createRadios("a");
createRadios("b");
createRadios("d");
} else if (randomRadio === 2) {
createRadios("a");
createRadios("b");
createRadios("c");
createRadios("d");
} else {
createRadios("b");
createRadios("a");
createRadios("c");
createRadios("d");
}
1 Answer
Hugo Paz
15,622 PointsMy suggestion:
Add all function to an array, something like this:
var rArray = ["a", "b", "c", "d"];
Then shuffle the array
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
And finally do a for loop passing the array order to the createRadio function