基于其他用户给出的条件的随机值
Random value based on a condition given by other user
我正在尝试改变饮食应用程序,我们有一个由营养师创建的膳食列表,以便用户可以根据定义的机会获得不同的膳食,例如:
Rice and egg = 40%
Rice and chicken = 40%
Free to choose = 10%
Rice and steak = 5%
Pasta and Fried chicken = 5%
我有一种很酷的方式向用户展示它,但没有有效的代码来做出决定。
如果有人能在这里提供帮助,我们会很高兴
您可以使用 this 算法根据给定的概率随机找到一顿饭。
实施:
fun getRandomMeal(meals: List<String>, probabilities: List<Int>): String {
val cumulativeProbabilities = probabilities.runningFold(0, Int::plus)
val random = (1..100).random()
meals.forEachIndexed { i, meal ->
if (cumulativeProbabilities[i + 1] >= random)
return meal
}
return ""
}
我正在尝试改变饮食应用程序,我们有一个由营养师创建的膳食列表,以便用户可以根据定义的机会获得不同的膳食,例如:
Rice and egg = 40%
Rice and chicken = 40%
Free to choose = 10%
Rice and steak = 5%
Pasta and Fried chicken = 5%
我有一种很酷的方式向用户展示它,但没有有效的代码来做出决定。
如果有人能在这里提供帮助,我们会很高兴
您可以使用 this 算法根据给定的概率随机找到一顿饭。
实施:
fun getRandomMeal(meals: List<String>, probabilities: List<Int>): String {
val cumulativeProbabilities = probabilities.runningFold(0, Int::plus)
val random = (1..100).random()
meals.forEachIndexed { i, meal ->
if (cumulativeProbabilities[i + 1] >= random)
return meal
}
return ""
}