我想到的方法是: int a; int b; int c; do { a = arc4random() % 49; } while ((a == x) || (a == y)); do { b = arc4random() % 49; } while ((b == x) || (b == y) || (b == a)); do { c = arc4random() % 49; } while ((c == x) || (c == y) || (c == a) || (c == b));但这对我来说似乎有点不好,我不知道,我只是想学习成为一个更好的程序员,对于最佳实践而言,最优雅的方法是什么?解决方案您可以使用 Fisher-Yates洗牌.这是一种有效的算法,可以从某个集合中生成一个随机排序的值列表.您首先要从要获取随机值的值列表中排除N,然后执行随机播放.I have 2 numbers which are between 0 and 49. Let's call them x and y. Now I want to get a couple of other numbers which are not x or y, but are also between 0 and 49 (I am using Objective C but this is more of a general theory question I think?).Method I thought of is: int a; int b; int c; do { a = arc4random() % 49; } while ((a == x) || (a == y)); do { b = arc4random() % 49; } while ((b == x) || (b == y) || (b == a)); do { c = arc4random() % 49; } while ((c == x) || (c == y) || (c == a) || (c == b));But it seem kind of bad to me, I don't know, I am just trying to learn to be a better programmer, what would be the most elegant way to do this for best practices? 解决方案 You can use something called the Fisher-Yates shuffle. It's an efficient algorithm for producing a randomly ordered list of values from some set. You would first exclude N from the list of values from which to get random values, and then perform the shuffle. 这篇关于如何有效地从1到50中选择几个唯一的随机数(不包括x)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 16:12