如何增加从数组中获取特定随机对象的可能性

时间:2022-01-15 19:40:07

Generally, I know that I can get a random element of an array in the following way:

一般来说,我知道我可以通过以下方式获取数组的随机元素:

var myArray = [x, y, z]
let myArrayLength = UInt32(myArray.count)
let myArrayIndex = Int(arc4random_uniform(myArrayLength))
let randomElement = myArray[myArrayIndex]

But how can I make the possibility of y being the random element twice the possibility of x and z being the random element thrice the possibility of y?

但是,我怎样才能使y成为随机元素两倍的可能性x和z是随机元素的三倍y的可能性?

UPDATE

UPDATE

NB: Where x, y and z are CGPoints

注意:其中x,y和z是CGPoints

1 个解决方案

#1


2  

An easy way is to rewrite your array like this: [x,x,y,z]. Then, the probability of getting x becomes 0.5, the probability of y becomes 0.25 and the probability of z becomes 0.25. Just repeat the symbols with high probability as much as you want, for example [x, y, y, z, z, z, z] is good for what you asked for.

一种简单的方法是重写你的数组:[x,x,y,z]。然后,获得x的概率变为0.5,y的概率变为0.25并且z的概率变为0.25。只要你想要的概率很高的重复符号,例如[x,y,y,z,z,z,z]对你要求的是好的。

#1


2  

An easy way is to rewrite your array like this: [x,x,y,z]. Then, the probability of getting x becomes 0.5, the probability of y becomes 0.25 and the probability of z becomes 0.25. Just repeat the symbols with high probability as much as you want, for example [x, y, y, z, z, z, z] is good for what you asked for.

一种简单的方法是重写你的数组:[x,x,y,z]。然后,获得x的概率变为0.5,y的概率变为0.25并且z的概率变为0.25。只要你想要的概率很高的重复符号,例如[x,y,y,z,z,z,z]对你要求的是好的。