我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
当前回答
使用underscore.js库。对于这种情况,方法_.shuffle()很好。以下是该方法的示例:
var _ = require("underscore");
var arr = [1,2,3,4,5,6];
// Testing _.shuffle
var testShuffle = function () {
var indexOne = 0;
var stObj = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5
};
for (var i = 0; i < 1000; i++) {
arr = _.shuffle(arr);
indexOne = _.indexOf(arr, 1);
stObj[indexOne] ++;
}
console.log(stObj);
};
testShuffle();
其他回答
我找不到我喜欢的。这是我想出的解决方案。我没有使用太多无意义的变量,因为这是我现在的编码方式。
Array.prototype.shuffle = function() {
for (let i in this) {
if (this.hasOwnProperty(i)) {
let index = Math.floor(Math.random() * i);
[
this[i],
this[index]
] = [
this[index],
this[i]
];
}
}
return this;
}
让arrayA=[“item1”、“item2”、“item3”、“Item 4”、“Items5”];Array.prototype.shuffle=函数(){为了(让我进来){如果(this.hasOwnProperty(i)){让index=Math.floor(Math.random()*i);[这个[i],此[索引]] = [该[索引],本[i]];}}返回此;}console.log(arrayA.shuffle());
我希望这能帮助那些可能不太理解这一点的人。
所有其他答案都基于Math.random(),它很快,但不适用于密码级别的随机化。
下面的代码使用了众所周知的Fisher Yates算法,同时利用Web Cryptography API实现了随机化的加密级别。
变量d=[1,2,3,4,5,6,7,8,9,10];函数洗牌(a){var x,t,r=新Uint32Array(1);对于(var i=0,c=a.length-1,m=a.length;i<c;i++,m-){crypto.getRandomValues(r);x=数学楼层(r/65536/65536*m)+i;t=a[i],a[i]=a[x],a[x]=t;}返回a;}console.log(shuffle(d));
考虑将其应用于本地或新的不可变数组,遵循其他解决方案,以下是建议的实现:
Array.prototype.shuffle = function(local){
var a = this;
var newArray = typeof local === "boolean" && local ? this : [];
for (var i = 0, newIdx, curr, next; i < a.length; i++){
newIdx = Math.floor(Math.random()*i);
curr = a[i];
next = a[newIdx];
newArray[i] = next;
newArray[newIdx] = curr;
}
return newArray;
};
我发现这个变体挂在“作者删除”的答案中,重复了这个问题。与其他一些已经获得许多支持的答案不同,这是:
实际上是随机的不到位(因此名称被打乱而不是打乱)此处尚未出现多个变体
这是一个jsfiddle,显示了它的使用情况。
Array.prototype.shuffled = function() {
return this.map(function(n){ return [Math.random(), n] })
.sort().map(function(n){ return n[1] });
}
您可以轻松地使用地图和排序:
让unshuffled=['hello','a','t','q',1,2,3,{cats:true}]让洗牌.map(value=>({value,sort:Math.random()})).sort((a,b)=>a.sort-b.sort).map(({value})=>值)console.log(混洗)
我们将数组中的每个元素放在一个对象中,并给它一个随机排序键我们使用随机键排序我们取消映射以获取原始对象
您可以对多态数组进行排序,排序就像Math.random一样随机,这对于大多数目的来说都足够好。
由于元素是根据每次迭代都不会重新生成的一致键进行排序的,并且每次比较都来自相同的分布,因此Math.random分布中的任何非随机性都会被取消。
速度
时间复杂度为O(N log N),与快速排序相同。空间复杂度为0(N)。这不像Fischer Yates洗牌那样高效,但在我看来,代码明显更短,功能更强大。如果你有一个大数组,你当然应该使用Fischer Yates。如果您有一个包含几百个项目的小数组,您可以这样做。