运行随机数并保持状态 [英] run for random numbers and keep state

查看:84
本文介绍了运行随机数并保持状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码从指定范围内获取随机值

I use the following code to get random value from specifed range

var provideRanges = function(){
    var aa = [];
    _.times(3, function(i) {
      console.log(i);
      let num = _.random(10, 20)
      console.log("num = :" + num)
      debugger;
      aa.push(num);
      console.log("value is :" + aa[i]);
    });
}

这是可行的,并在您调用此函数时在指定范围内提供3个值的数组,但是当我需要再次调用它时,这里的问题变得更加棘手,请忽略上一个提供的数字中提供的数字(例如,如果下次不提供这些数字,则提供10,11,12 ...),还有更好的方法吗?我尝试使用回叫电话,但迷路了:(,有什么想法吗?

This is working and provide array of 3 values between the specified range when you call to this function, but the problem here become more difficult when I need that if I call it again ignore exclude the previous provided number from the provided numbers (like if it provide 10,11,12 the next time those numbers should not be provided...), is there is nicer way to do it? I try to use recoursive call but get lost:( ,any idea how to do it?

推荐答案

一种方法是创建一个数组来存储现有选择,将所选元素推入数组,检查该数组是否包含该元素以及该数组是否存储值.length大于或等于最大范围减去最小范围.

One approach would be to create an array to store existing selections, push selected elements to an array, check if the array contains the element and if the array storing values .length is greater than or equal to maximum range minus minimum range.

根据问题的描述尚不清楚,一旦返回范围中的所有元素该怎么办?

It is not clear from description at Question what should occur once all of the elements in the range have been returned?

var range = [10, 20];
var not = [];

function randomRange(range, n) {
  if (not.length >= range[1] - range[0]) {
    return "all numbers in range used"
  }
  var curr = [];
  var res = [];
  for (let i = range[0]; i < range[1]; i++) {
    if (!not.some(function(num) {
      return i == num
    }) && not.length < range[1] - range[0]) {
      curr.push(i)
    }
  }
  for (let i = 0; i < n; i++) {
    var j = curr.splice(Math.floor(Math.random() * curr.length), 1)[0];
    res[i] = not[not.length] = j;
  }

  return res.filter(Boolean)
}

console.log(randomRange(range, 3));
console.log(randomRange(range, 3));
console.log(randomRange(range, 3));
console.log(randomRange(range, 3));
console.log(randomRange(range, 3));

这篇关于运行随机数并保持状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆