从1-9之间的随机数字列表中选出3个相同的数字

3 numbers the same from a random numbers list between 1-9

本文关键字:数字 3个 列表 之间 随机      更新时间:2023-09-26

如果我有一个数组,从9个数字的列表中给我9个随机数,我如何确保它只能重复3个相同的数字?例如,如果我的随机数数组是[4,3,4,7,8,8,9]。我需要在任何一个数组中只有一个三元组,而不是像上面看到的那样有两个。

您需要将randomNum替换为用于存储添加到数组中的随机数的任何内容,但请尝试以下操作:

var arrayOfRandomNums = [];
function maxInstancesInArray(arr, val) {
    var hits = [];
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val)
            indexes.push(i);
    return indexes.length > 2;
}
if(!maxInstancesInArray(arrayOfRandomNums, randomNum) {
    arrayOfRandomNums.push(randomNum);
}

如果数组中已经有3个或更多传入数字的实例,则函数将返回true,因此您可以使用它来定义是否将下一个实例推送到数组中。

我制作了一个jsFiddle,它可以提供帮助。这个想法是,与其每次都试图获取rundom数字并进行检查,不如在数组中列出可用数字的列表,并随机选择该数组的索引。

https://jsfiddle.net/m8ohmxmb/

  function randNumber(maxRange,maxOccurrencies, resultArrayLenght) {
     var num = [];
     var occ = [];
     var result = [];
     var randElem;
     for (var i = 0; i < maxRange; i++) {
        num.push(i + 1);
        occ.push(0);
     }
     for(i = 0; i < resultArrayLenght; i++) {
         randElem = Math.floor(Math.random() * num.length);  
         occ[randElem] = occ[randElem] + 1;
         result.push(num[randElem]);
         if(occ[randElem] === maxOccurrencies) {
             occ.splice(randElem,1);
             num.splice(randElem,1);
         }
     }
     return result;
  }

这是一种直接的方法,使用一个临时对象来保存insertet值及其计数。

function push(n) {
    if (count.full && count[n] === 2) {
        alert('can not insert ' + n);
        return;
    }
    array.push(n);
    count[n] = (count[n] || 0) + 1;
    if (count[n] === 3) {
        count.full = true;
    }
}
var array = [],
    count = {};
[4, 3, 4, 4, 7, 8, 8, 8, 9].forEach(push);
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');