不同数组的随机组合,不重复



对网站和javascript非常陌生。在论坛上找了一段时间,但找不到我想要的答案,或者至少不能理解我读过的线程。

我试图使一个生成器创建尽可能多的组合需要上面的数组,而不重复组合,每次迭代只使用每个数组的一个项目。我还需要添加一些额外的需求,例如迭代的唯一id和标记迭代的额外属性,其中所有属性具有相同的值。

代码

var accesories = ["pijama" , "urban" , "joker" , "joyboy" , "crypto"];
var hats = accesories;
var tshirts = accesories;
var boots = accesories;

var cards = [];
function randomizeParts() {
model.accesories = accesories[Math.floor(Math.random() * 5)];
model.hats = hats[Math.floor(Math.random() * 5)];
model.tshirts = tshirts[Math.floor(Math.random() * 5)];
model.boots = boots[Math.floor(Math.random() * 5)];
};

function addInsomnio (quantity) {
for (let i = 1 ; i <= quantity ; i++){
model = {
id : 0,
accesories: 0,
hats: 0,
tshirts: 0,
boots: 0}
//adding four digits id
i < 10 ? model.id = '000' + i : i < 100 ? model.id = '00' + i : i < 1000 ? model.id = '0' + i : i <= 10000 ? model.id = i :false;
//randomizing parts
randomizeParts() 
//checking if rarity was generated
model.accesories === model.hats && model.accesories === model.tshirts && model.accesories === model.boots ? model.rarity = "original" : false;

//checking its unique

// ????
//Pushing a beautifull brand new and unique card
cards.push(model);
}
};

有没有办法比较随机模型中的现有对象如果这个组合已经存在,那么在按下它之前再随机化几次?

注意:这计划只使用一次,以生成10,000项json作为ps脚本的支持。

您可以用一个唯一的数字标识每个组合,并维护一组已使用的数字:

function choices(count, ...arrays) {
let used = new Set;
let size = arrays.reduce((size, arr) => size * arr.length, 1);
if (count > size) count = size;
let result = [];
for (let i = 0; i < count; i++) {
let k;
do {
k = Math.floor(Math.random() * size);
} while (used.has(k));
used.add(k);
result.push(arrays.reduce((acc, arr) => {
acc.push(arr[k % arr.length]);
k = Math.floor(k / arr.length);
return acc;
}, []));
}
return result;
}
let accesories = ["a", "b", "c", "d", "e"];
let hats = ["A", "B", "C", "D", "E"];
let tshirts = ["1", "2", "3", "4", "5"];
let boots = [".", ";", "?", "!"];
// Get 10 choices:
let result = choices(10, accesories, hats, tshirts, boots);
console.log(result);

最新更新