非重复arc4random_uniform [英] Non-repeating arc4random_uniform

查看:91
本文介绍了非重复arc4random_uniform的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使非重复性的arc4random_uniform可以在我的iPhone应用程序上使用很长时间.运气好了,在stackoverflow上解决了与此相关的所有问题和答案,现在我希望有人能帮助我.我想做的是从1到104之间选择13个不同的随机数.我已经选择了13个不同的数字,但有时其中两个是相同的.

I've been trying to get non-repeating arc4random_uniform to work for ages now for my iPhone app. Been over all the questions and answers relating to this on stackoverflow with no luck and now I'm hoping someone can help me. What I want to do is is choose 13 different random numbers between 1 and 104. I have gotten it to work to the point of it choosing 13 different numbers, but sometimes two of them are the same.

int rand = arc4random_uniform(104);

这就是我正在做的,然后我使用rand从数组中选择.如果改组数组然后从顶部选择13更容易,那么我会尝试一下,但是我会需要如何做的帮助,因为这似乎很难.

This is what I'm doing, and then I'm using the rand to choose from an array. If it's easier to shuffle the array and then pick 13 from the top, then I'll try that, but I would need help on how to, since that seems harder.

感谢您的任何建议.

推荐答案

不能保证ar4random_uniform()不会重复.仔细考虑一下-您要让它产生一个介于0和103之间的数字.如果重复执行一百零五次,则它只能重复以前的选择之一.该函数如何知道您要请求一个号码多少次?

There's no guarantee whatsoever that ar4random_uniform() won't repeat. Think about it for a second -- you're asking it to produce a number between 0 and 103. If you do that one hundred and five times, it has no choice but to repeat one of its earlier selections. How could the function know how many times you're going to request a number?

您将不得不检查已经获得的数字列表,如果重复则请求一个新的数字,或者将数组改组.为此,应该有许多关于SO的问题.这是最古老的之一:改组NSMutableArray的最佳方法是什么?.

You will either have to check the list of numbers that you've already gotten and request a new one if it's a repeat, or shuffle the array. There should be any number of questions on SO for that. Here's one of the oldest: What's the Best Way to Shuffle an NSMutableArray?.

关于非重复随机数,还有很多问题: https://stackoverflow.com/search?q=%5Bobjc%5D+non-repeating+random+numbers

There's also quite a few questions about non-repeating random numbers: https://stackoverflow.com/search?q=%5Bobjc%5D+non-repeating+random+numbers

这篇关于非重复arc4random_uniform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆