JavaScript如何生成多数组无重复随机组合并校验对象唯一性
解决方案
前置提醒
你当前四个部位(配饰、帽子、T恤、靴子)的可选值都取自长度为5的accesories数组,所有可能的唯一组合总数只有 5^4 = 625 种,无法生成10000条不重复的组合。如果确实需要10000条唯一数据,请先扩充每个部位的可选值数组长度。
核心实现思路
- 用
Set存储已生成组合的特征字符串,判断重复的时间复杂度为O(1),比遍历数组逐一对比对象属性效率高很多 - 每次生成新组合后,先拼接四个部位的取值作为特征字符串,判断是否已存在,存在就重新生成,不存在再存入结果数组
- 补充最大生成量判断,避免目标数量超过可生成上限时进入无限循环
修正后完整代码
const accesories = ["pijama" , "urban" , "joker" , "joyboy" , "crypto"]; const hats = accesories; const tshirts = accesories; const boots = accesories; const cards = []; // 存储已生成的组合特征,用于去重 const existingCombinations = new Set(); // 计算当前最多可生成的唯一组合数量 const maxPossibleCombinations = accesories.length * hats.length * tshirts.length * boots.length; function addInsomnio (quantity) { // 目标数量超过可生成上限时,取最大值 const target = Math.min(quantity, maxPossibleCombinations); while (cards.length < target) { // 生成四部位随机值 const randomAcc = accesories[Math.floor(Math.random() * accesories.length)]; const randomHat = hats[Math.floor(Math.random() * hats.length)]; const randomTshirt = tshirts[Math.floor(Math.random() * tshirts.length)]; const randomBoot = boots[Math.floor(Math.random() * boots.length)]; // 拼接组合特征字符串 const combinationKey = `${randomAcc}|${randomHat}|${randomTshirt}|${randomBoot}`; // 重复则跳过本次循环,重新生成 if (existingCombinations.has(combinationKey)) continue; // 不重复则存入特征集合,构建model对象 existingCombinations.add(combinationKey); const currentId = String(cards.length + 1).padStart(4, '0'); const model = { id: currentId, accesories: randomAcc, hats: randomHat, tshirts: randomTshirt, boots: randomBoot }; // 稀有度判断 if (randomAcc === randomHat && randomAcc === randomTshirt && randomAcc === randomBoot) { model.rarity = "original"; } cards.push(model); } // 生成完成后可以直接导出JSON // console.log(JSON.stringify(cards, null, 2)) } // 调用示例,最多生成625条唯一数据 addInsomnio(10000);
其他说明
如果你不需要严格的组合去重,只是要生成10000条数据,删除existingCombinations相关的去重逻辑即可。
内容的提问来源于stack exchange,提问作者Joyboy
相关产品推荐
相关产品推荐

