繁体   English   中英

从数组创建随机数组

[英]Create random arrays from an array

假设我有16个数字,范围从0到15。它们位于一个数组中。 我要实现的是以下数组:

  1. 具有3个随机数的数组。
  2. 具有2个随机数的数组。
  3. 具有3个随机数的数组。
  4. 具有2个随机数的数组。
  5. 具有2个随机数的数组。
  6. 具有3个随机数的数组。

我将称之为masterarray的数字只能使用一次。 因此,数组x保持1、5和7,数组y保持2、9(这些应该是完全随机的)。

我知道我可以使用indexOfsplice从数组中获取和删除项目。 但是我该如何从数组中获取随机数,同时又将其从列表中删除呢?

因为在此过程中更改了数组,所以foreach不会进行。 据我了解,for-loop也是如此。

我该如何实现?

这是一种非随机的方法...

var master = [], arr1=[], arr2=[], arr3=[], arr4=[], arr5=[], arr6=[], i=1;

for(i; i<16;i++){  // populating "master" array
master.push(i); 
}


while(master.length>0){
var num =master.splice(Math.floor(Math.random()*master.length),1)[0];
if (master.length>11){
arr1.push(num);
continue;
}
if(master.length>9){
arr2.push(num);
continue;
}
if(master.length>6){
arr3.push(num);
continue;
}
if(master.length>4){
arr4.push(num);
continue;
}
if(master.length>2){
arr5.push(num);
continue;
}
else {
arr6.push(num);
}
}
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
console.log(arr5);
console.log(arr6);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM