产生非重复的随机数 [英] Generating non-repeating random numbers

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

问题描述

我想创建一个函数C.它会在范围内N个像返回一个随机整数: -
兰特()%N;
但事情是我想要跟踪的独特性。我不想号码重复。但我也可以做一个数组,并在其复制生成的整数做到这一点。喜欢 :-
数组[统计] =兰特()%N; ,检查每次如果该号码产生已经在它里面与否。 (简单地通过数组[]内搜索的话);这是一个简单的方法,但正确的。如果公司以及公司将采取多;这个工作。
这是最好的,我可以拿出。

I want to create a function in C. It will return a random integer in-range of N like:- rand() % N; but the thing is I want to keep track of uniqueness. I don't want the numbers to repeat. but i can also do this by making an array and copying the generated integers in it. like :- array[count] = rand() % N; and check every time if the number generated was already inside it or not. (simply by searching it inside the array[]); this is a simple approach but a correct one. it will take many if's and for's; for this to work. this is the best i can come up with.

的事情是,我要得到这个问题的最佳/优化的解决方案。会是怎样做到这一点的最有效方法是什么?

让清晰的一些事情 -
我想设置在从NSArray中一个UILabel,始终是独一无二的一些文字。我的NSArray从plist中获取数据,而我的plist拥有超过1000个条目。如果我想要做了很多次,所以我想要一些有效的方式做到这一点会影响性能。

推荐答案

这听起来像你想要什么是真正的数字1..N的随机排列。因此,填充的连续整数1..N的数组,然后洗牌数组。有洗牌,你可以看一下众所周知的算法。

It sounds like what you want is really a random permutation of the number 1..N. So, fill an array with consecutive integers 1..N and then shuffle the array. There are well known algorithms for shuffling that you can look up.

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

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