问题描述
我有一个对象数组,像这样.
I have an Array of Objects, like so.
var usersGoing = [
{ user: 0 },
{ user: 1 },
{ user: 2 },
{ user: 3 },
{ user: 4 }
];
我需要重新整理此Array,以便没有对象与实例化时在同一索引中,就像这样:
I need to shuffle this Array so that no Object remains in the same index as when it was instantiated, like so:
[
{ user: 3 },
{ user: 2 },
{ user: 4 },
{ user: 0 },
{ user: 1 }
]
必须以这种方式对结果数组进行排序,因为这些用户对象中的每一个都将分配给不同的用户对象.
It is IMPERATIVE that the resulting array be sorted in this manner, as each of these user Objects will be assigned to a different user Object.
我尝试了几种不同的排序算法,包括Fisher-Yates,并且尝试使用Underscore.js的_.shuffle()和Kirupa的此变体使用JavaScript整理数组:
I have tried a few different sorting algorithms, including Fisher-Yates, and I've tried using Underscore.js' _.shuffle(), and this variant from Kirupa Shuffling an Array in JavaScript:
function shuffleFY(input) {
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
我尝试过的一切都没有用.帮助吗?
Nothing I've tried is working. Help?
更新:我已在下面将答案标记为正确,因为正确遵循了《萨图洛循环》的要点.此外,这不是的重复项在Javascript/PHP中,因为该问题对结果数组的附加要求不仅是不包含重复项,而且不能在其初始索引位置处包含项.
UPDATED: I've marked an answer as correct below, as the key points of the Sattolo Cycle were followed correctly. Also, this is NOT a duplicate of Shuffles Random Numbers with no repetition in Javascript/PHP as this question has the additional requirement of the resulting array not only not containing duplicates, but also cannot contain items in their same initial index position.
推荐答案
您在Python中发布了Sattolo算法的链接:
You posted a link with Sattolo's algorithm in Python:
from random import randrange
def sattoloCycle(items):
i = len(items)
while i > 1:
i = i - 1
j = randrange(i) # 0 <= j <= i-1
items[j], items[i] = items[i], items[j]
return
此处已翻译为JavaScript:
Here it is translated to JavaScript:
function sattoloCycle(items) {
for(var i = items.length; i-- > 1; ) {
var j = Math.floor(Math.random() * i);
var tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
这篇关于如何对Javascript数组进行混洗以确保每个索引在新数组中都处于新位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!