选择随机数的快速概率?

我正在尝试制作一款游戏,您可以在其中升级您的特定项目.新项目的质量将是随机的,并基于以下内容:

10% worse - 35% better then current item level = 55% chance
36% better to 90% better then current item level = 35% chance
91% better to 200% better then current item level = 5% chance
201% better to 500% better then current item level = 2.5% chance
500% better to 2000% better then current item level = 2.5% chance

我怎样才能使它生成一个随机数,例如,55%的几率只有35%?我有一个破解并想出了这个(忽略%数字,我只是用这个来测试).

let randomNumber = Int(arc4random_uniform(1000))


if randomNumber <= 700 {
    println("hey")
    var newLevel = (Double(Double(randomNumber) / 700.00) + 0.1) * Double(pickDamage)

} else if randomNumber <= 800 && randomNumber > 700 {
    var newLevel = (Double(Double(randomNumber) / 700.00) + 1.00) * Double(pickDamage)
} else if randomNumber <= 1000 && randomNumber > 950 {
    var newLevel = (Double(Double(randomNumber) / 700.00) + 2.00) * Double(pickDamage)
}

但这并不是我想要的方式.

最佳答案
为什么不将Swift switch语句与模式匹配结合使用:

// create a random percent, with a precision of one decimal place
func randomPercent() -> Double {
  return Double(arc4random() % 1000) / 10.0;
}

let randomNumber = randomPercent()
switch(randomNumber) {
case 0..<55:
  println("10% worse - 35% better then current item level")
case 55..<90:
  println("36% better to 90% better then current item level")
case 90..<95:
  println("91% better to 200% better then current item level")
case 95..<97.5:
  println("201% better to 500% better then current item level")
default:
  println("500% better to 2000% better then current item level")
}

这使得逻辑非常清晰.

转载注明原文:选择随机数的快速概率? - 代码日志