I have an array that has been randomised and repeated X times. How can I ensure for each iteration that the last item in the array is not the same as in the previous iteration?
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;
}
var arr = [1, 2, 3, 4, 5, 6];
for(var i = 0; i < 6; i++) {
shuffle(arr);
console.log(arr);
}
Example output:
[5, 6, 3, 4, 1, 2]
[4, 3, 2, 6, 1, 5]
[6, 1, 3, 4, 5, 2]
[1, 5, 4, 6, 3, 2] // Last item in array is same as last item in previous array
[6, 3, 5, 4, 2, 1]
[2, 4, 5, 3, 1, 6]
What I'd like to be output:
[5, 6, 3, 4, 1, 2]
[4, 3, 2, 6, 1, 5]
[6, 1, 3, 4, 5, 2]
[1, 5, 2, 6, 3, 4] // Last item in array is different to last item in previous array
[6, 3, 5, 4, 2, 1]
[2, 4, 5, 3, 1, 6]
I'm guessing I need to do something along the lines of storing the previous and current arrays in a temporary variable but have so far been unsuccessful at generating the correct logic. Any help would be greatly appreciated
Aucun commentaire:
Enregistrer un commentaire