【问题标题】:Javascript - Multiple Unequal Random Number GeneratorJavascript - 多个不等随机数生成器
【发布时间】:2017-09-22 18:36:31
【问题描述】:

我正在尝试编写一个在给定范围内产生四个不相等随机数的函数,但该函数当前在while (selection[i] in selection.slice().splice(i) 行失败。这一行应该检查当前 (i'th) 值是否被任何其他随机值共享,但目前它似乎什么也没做——也许我错误地使用了in?任何帮助将不胜感激。

function contains(a, obj) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] === obj) {
    return true;
    }
  }
  return false;
}

selected=[];

function randomSelection() {

  var notselected=[];
  for (var i=0; i<25; i++) {
    if(!contains(selected, i)) {
        notselected.push(i);
    }
  }
  var selection=[notselected[Math.floor(Math.random() * notselected.length)],
                             notselected[Math.floor(Math.random() * notselected.length)],
                             notselected[Math.floor(Math.random() * notselected.length)],
                             notselected[Math.floor(Math.random() * notselected.length)]];

  for (var i=0; i<selection.length; i++) {
    while (selection[i] in selection.slice().splice(i)) {
      alert('Hello!')
      selection[i] = notselected[Math.floor(Math.random() * notselected.length)];
    }
  }
  for (var i=0; i<selection.length; i++) {
    selected.pop(selection[i]);
  }
}

【问题讨论】:

    标签: javascript canvas random slice splice


    【解决方案1】:

    随机打乱一组对象(本例中为数字)

        var values = [0,1,2,3,4,5,6];
        function shuffle(arr){
            var temp = [...arr];
            arr.length = 0;
            while(temp.length > 0){
                arr.push(temp.splice(Math.floor(Math.random() * temp.length),1)[0]);
            }
            return arr;
        }
        console.log("pre shuffle : [" + values.join(", ") + "]"); 
        shuffle(values);
        console.log("post shuffle : [" + values.join(", ") + "]"); 

    【讨论】:

      【解决方案2】:

      您可以使用以下方法获得两个数字之间的随机值

      function getRandomArbitrary(min, max) {
         return Math.floor(Math.random() * (max - min)) + min;
      }
      

      如果值需要是整数可以使用以下方法:

      function getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min)) + min;
      }
      

      所以,假设您需要 4 个不同的随机整数值,您可以这样做

      var randoms = [];
      while(randoms.length < 4) {
      
        var random = getRandomInt(0, 25);
      
        if(randoms.indexOf(random) === -1) {
          randoms.push(random);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-03
        • 2016-07-22
        • 1970-01-01
        • 2017-10-22
        • 2013-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多