我有一个已经随机化并重复X次的数组。如何确保每次迭代时,数组中的最后一项与上一次迭代中的不一样?
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);
}
示例输出:
[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]
我希望输出的内容:
[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]
我猜我需要做一些事情,就像在临时变量中存储前一个和当前数组一样,但到目前为止还没有成功生成正确的逻辑。任何帮助将不胜感激
答案 0 :(得分:0)
你可以使用while循环。
while(new_array[new_array.length - 1] == old_array[old_array.length - 1]) {
// Do some randomising
}
显然,将这个随机称为有点延伸。
答案 1 :(得分:0)
所以每次遇到问题时都要向左推,这里是一个使用previousLast全局变量的解决方案(也许你应该将所有类都包装在一个更干净的类中):
var arr = [1, 2, 3, 4, 5, 6];
var previousLast = 0;
for(var i = 0; i < 60; i++) {
// here you should reassign arr because, if arr is rolled, this is a new array.
arr = shuffle(arr);
console.log(arr);
}
function rollLeft(a) {
var b = [];
for(var i = 0, n = a.length; i < n; ++i) {
b.push(a[(i + 1) % n]);
}
return b;
}
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;
}
if(array[array.length - 1] == previousLast) {
array = rollLeft(array);
}
previousLast = array[array.length - 1];
return array;
}