[英]Randomize numbers from a specific array without duplicates
I have a array shuffled with some numbers I want to randomize the numbers in shuffled array without duplication am using below code 我有一个混排有一些数字的数组,我想将混洗后的数组中的数字随机化而不重复使用以下代码
int shuffled array [] = {1,3,5,7,8}
Random random = new Random();
int random =shuffled array[random.nextInt(shuffled array.length)];
I am getting duplicate values. 我得到重复的值。
How do I get to generate random number without any duplicate values? 如何生成没有任何重复值的随机数?
In general you can do in of the following: 通常,您可以执行以下操作:
Set
so that they are unique and keep pooling them until the desired amount of random numbers is achieved. 创建随机数并将其保存在Set
以便它们是唯一的,并不断合并它们,直到获得所需数量的随机数为止。 Edit: 编辑:
About efficiency (if you are concerned about it): The first method uses a pseudorandom generator to produce the unique numbers. 关于效率(如果您对此有所担心):第一种方法使用伪随机数生成器来生成唯一数字。 As the number of unique number in respect to the total possible numbers increases, (eg if you have an array and want all element to be picked up at random) then this approach might be inappropriate. 随着唯一数相对于可能总数的增加,(例如,如果您有一个数组并希望随机拾取所有元素),则此方法可能不合适。 If on the other hand you just want to pick 10 unique random numbers it is possibly efficient enough. 另一方面,如果您只想选择10个唯一的随机数,则可能足够有效。
The shuffle
approach as states This method runs in linear time so it should be preferred in this case (yours that is). 作为状态的shuffle
方法此方法以线性时间运行,因此在这种情况下(即您所愿)应该是首选方法 。
int pos =shuffled array[random.nextInt(4)]
int random_num_from_shuffled_array = shuffled array[pos];
Create a Collection
( Set
- because of the no-duplicates requirement) using your array. 使用您的阵列创建一个Collection
( Set
因为没有重复项)。 Use Collections.shuffle(mySet);
使用Collections.shuffle(mySet);
You are actually using the Random
class and nextInt
which do not guarantee uniqueness of consecutive elements! 您实际上正在使用Random
类和nextInt
,它们不能保证连续元素的唯一性!
I guess what you need is achieved by Collections.shuffle
. 我想您所需要的是通过Collections.shuffle
实现的。 See the documentation 请参阅说明文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.