【问题标题】:Creating a Javascript function that returns random integers but with a specified distribution/"weight"创建一个返回随机整数但具有指定分布/“权重”的 Javascript 函数
【发布时间】:2017-11-02 09:59:53
【问题描述】:

我有一个值数组:

var my_arr = [/*all kinds of stuff*/]

我有一个生成随机数的函数,我用它作为my_arr中元素的索引...

var RandomFromRange = function (min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
};

...所以我可以这样做:

my_arr[RandomFromRange(0,my_arr.length)];

我想要做的是将my_arr 中的某些元素指定为具有“优先级”,以便RandomFromRange 返回 5,例如 25% 的时间,返回 4、14% 的时间,然后返回任何其他数字...

(100 - 25 - 14)/(my_arr.length - 2)

...% 的时间。

在我做研究的时候,我遇到了几个poststhat describesimilar problems,但他们的答案不是Javascript,而且我还没有足够的数学知识来理解他们的一般原则。任何建议将不胜感激。

【问题讨论】:

标签: javascript probability non-uniform-distribution


【解决方案1】:

这可能不像您要寻找的那样准确,但这确实有效。基本上,这段代码会返回一个从最小值和最大值指定的随机数,就像你的一样,但只有在根据给定的机会解决优先级数字之后。

首先,我们必须您在代码中的优先级编号。如果你的优先级没有命中,那就是我们进行正常的RNG。

//priority = list of numbers as priority,
//chance = the percentage
//min and max are your parameters

var randomFromRange = function (min,max,priority,chance)
{
  var val = null; //initialize value to return
	
	for(var i = 0; i < priority.length; i++){ //loop through priority numbers
		
		var roll = Math.floor(Math.random()*100); //roll the dice (outputs 0-100)
		
		if(chance > roll){ ///check if the chance is greater than the roll output, if true, there's a hit. Less chance value means less likely that the chance value is greater than the roll output
			val = priority[i]; //make the current number in the priority loop the value to return;
			break; //if there's a hit, stop the loop.
		}
		else{
			continue; //else, keep looping through the priority list
		}
	}
	
  //if there is no hit to any priority numbers, return a number from the min and max range
	if(val == null){
		val = Math.floor(Math.random()*(max-min+1)+min);
	}
	
  //return the value and do whatever you want with it
	return val;
};

document.getElementsByTagName('body')[0].onclick = function (){
	console.log(randomFromRange(0,10,[20,30],50));
}
<!DOCTYPE html>
<html>
<body style='height: 1000px; width: 100%;'></body>
<script></script>
</html>

此代码对所有优先级数字数组应用一次机会。如果您希望优先级列表中的每个数字都有单独的机会,我们必须修改结构并将参数更改为包含类似内容的单个对象数组

var priorityList = [{num: 4, chance: 25},
                    {num: 5, chance: 12}]

【讨论】:

  • Merigold,我只是想感谢您为我的问题提供解决方案。我已经成功实现了你的代码,只做了很少的修改。
  • 很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 2014-11-05
  • 2012-04-29
  • 2021-03-02
  • 1970-01-01
  • 2022-11-16
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多