数组JAVA中的非重复随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21283198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Non-repeating random numbers inside array JAVA
提问by lazygeniusLANZ
I would like to generate 6 numbers inside an array and at the same time, having it compared so it will not be the same or no repeating numbers. For example, I want to generate 1-2-3-4-5-6 in any order, and most importantly without repeating. So what I thought is to compare current array in generated array one by one and if the number repeats, it will re-run the method and randomize a number again so it will avoid repeating of numbers.
我想在一个数组中生成 6 个数字,同时对其进行比较,这样它就不会相同或没有重复的数字。例如,我想以任何顺序生成 1-2-3-4-5-6,最重要的是不重复。所以我的想法是将生成的数组中的当前数组一一比较,如果数字重复,它将重新运行该方法并再次随机化一个数字,以避免重复数字。
Here is my code:
这是我的代码:
import javax.swing.*;
public class NonRepeat
{
public static void main(String args[])
{
int Array[] = new int [6];
int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
while(login != 0)
{
String output="";
for(int index = 0; index<6; index++)
{
Array[index] = numGen();
for(int loop = 0; loop <6 ; loop++)
{
if(Array[index] == Array[loop])
{
Array[index] = numGen();
}
}
}
for(int index = 0; index<6; index++)
{
output += Array[index] + " ";
}
JOptionPane.showMessageDialog(null, output);
}
}
public static int numGen()
{
int random = (int)(1+Math.random()*6);
return random;
}
}
I've been thinking it for 2 hours and still cant generate 6 numbers without repeating. Hope my question will be answered.
我已经想了 2 个小时,但仍然无法生成 6 个数字而不重复。希望我的问题能得到解答。
Btw, Im new in codes so please I just want to compare it using for
loop or while
loop and if else
.
顺便说一句,我是新的代码所以请我只想使用for
循环或while
循环和if else
.
采纳答案by Indra Yadav
Here is the solution according to your code -
这是根据您的代码的解决方案 -
You just need to change the numGen method -
你只需要改变 numGen 方法 -
public static int numGen(int Array[])
{
int random = (int)(1+Math.random()*6);
for(int loop = 0; loop <Array.length ; loop++)
{
if(Array[loop] == random)
{
return numGen(Array);
}
}
return random;
}
Complete code is -
完整的代码是——
import javax.swing.*;
public class NonRepeat
{
public static void main(String args[])
{
int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
while(login != 0)
{
int Array[] = new int [6];
String output="";
for(int index = 0; index<6; index++)
{
Array[index] = numGen(Array);
}
for(int index = 0; index<6; index++)
{
output += Array[index] + " ";
}
JOptionPane.showMessageDialog(null, output);
}
}
public static int numGen(int Array[])
{
int random = (int)(1+Math.random()*6);
for(int loop = 0; loop <Array.length ; loop++)
{
if(Array[loop] == random)
{
return numGen(Array);
}
}
return random;
}
}
回答by m0skit0
Use List
instead of array and List#contains
to check if number is repeated.
使用List
代替数组并List#contains
检查数字是否重复。
回答by TacticalCoder
You can generate numbers from, say, 1 to 6 (see below for another solution) then do a Collections.shuffle
to shuffle your numbers.
您可以从 1 到 6 生成数字(另一种解决方案请参见下文),然后执行 aCollections.shuffle
对您的数字进行洗牌。
final List<Integer> l = new ArrayList<Integer>();
for (int j = 1; j < 7; j++ ) {
l.add( j );
}
Collections.shuffle( l );
By doing this you'll end up with a randomized list of numbers from 1 to 6 without having twice the same number.
通过这样做,您最终会得到一个从 1 到 6 的随机数字列表,而不会有两次相同的数字。
If we decompose the solution, first you have this, which really just create a list of six numbers:
如果我们分解解决方案,首先你有这个,它实际上只是创建了一个包含六个数字的列表:
final List<Integer> l = new ArrayList<Integer>();
for (int j = 1; j < 7; j++ ) {
l.add( j );
}
So at this point you have the list 1-2-3-4-5-6 you mentioned in your question. You're guaranteed that these numbers are non-repeating.
因此,此时您拥有您在问题中提到的列表 1-2-3-4-5-6。您可以保证这些数字不会重复。
Then you simply shuffle / randomize that list by swapping each element at least once with another element. This is what the Collections.shuffle
method does.
然后,您只需通过将每个元素与另一个元素至少交换一次来简单地洗牌/随机化该列表。这就是该Collections.shuffle
方法的作用。
The solutions that you suggested isn't going to be very efficient: depending on how big your list of numbers is and on your range, you may have a very high probability of having duplicate numbers. In that case constantly re-trying to generate a new list will be slow. Moreover any other solution suggesting to check if the list already contains a number to prevent duplicate or to use a set is going to be slow if you have a long list of consecutive number (say a list of 100 000 numbers from 1 to 100 000): you'd constantly be trying to randomly generate numbers which haven't been generated yet and you'd have more and more collisions as your list of numbers grows.
您建议的解决方案不会非常有效:根据您的数字列表有多大以及在您的范围内,您可能有很高的概率出现重复的数字。在这种情况下,不断重新尝试生成新列表会很慢。此外,如果您有一个很长的连续数字列表(比如从 1 到 100 000 的 100 000 个数字的列表),建议检查列表是否已经包含一个数字以防止重复或使用集合的任何其他解决方案都会变慢:您会不断尝试随机生成尚未生成的数字,并且随着数字列表的增长,您会遇到越来越多的冲突。
If you do not want to use Collections.shuffle
(for example for learning purpose), you may still want to use the same idea: first create your list of numbers by making sure there aren't any duplicates and then do a for loop which randomly swap two elements of your list. You may want to look at the source code of the Collections.shuffle
method which does shuffle in a correct manner.
如果您不想使用Collections.shuffle
(例如出于学习目的),您可能仍想使用相同的想法:首先通过确保没有任何重复来创建您的数字列表,然后执行一个随机交换两个的 for 循环列表中的元素。您可能想查看以Collections.shuffle
正确方式进行 shuffle的方法的源代码。
EDITIt's not very clear what the properties of your "random numbers" have to be. If you don't want them incremental from 1 to 6, you could do something like this:
编辑您的“随机数”的属性不是很清楚。如果您不希望它们从 1 增加到 6,您可以执行以下操作:
final Random r = new Random();
final List<Integer> l = new ArrayList<Integer>();
for (int j = 0; j < 6; j++ ) {
final int prev = j == 0 ? 0 : l.get(l.size() - 1);
l.add( prev + 1 + r.nextInt(42) );
}
Collections.shuffle( l );
Note that by changing r.nextInt(42)
to r.nextInt(1)
you'll effectively get non-repeating numbers from 1 to 6.
请注意,通过更改r.nextInt(42)
为 ,r.nextInt(1)
您将有效地获得从 1 到 6 的非重复数字。
回答by xild
Use List and .contains(Object obj) method. So you can verify if list has the random number add before.
使用 List 和 .contains(Object obj) 方法。因此,您可以验证列表之前是否添加了随机数。
update - based on time you can lost stuck in random loop.
更新 - 根据时间,您可能会陷入随机循环。
List<Integer> list = new ArrayList<Integer>();
int x = 1;
while(x < 7){
list.add(x);
x++;
}
Collections.shuffle(list);
for (Integer number : list) {
System.out.println(number);
}
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)
回答by Darsh
You may use java.util.Random
. And please specify if you want any random number or just the number 1,2,3,4,5,6. If you wish random numbers then , this is a basic code:
您可以使用java.util.Random
. 并请说明您需要任何随机数还是仅需要数字 1、2、3、4、5、6。如果你想要随机数,这是一个基本代码:
import java.util.*;
public class randomnumber
{
public static void main(String[] args)
{
Random abc = new Random();
int[] a = new int[6];
int limit = 100,c=0;
int chk = 0;
boolean y = true;
for(;c < 6;)
{
int x = abc.nextInt(limit+1);
for(int i = 0;i<a.length;i++)
{
if(x==a[i])
{
y=false;
break;
}
}
if(y)
{
if(c!=0)if(x == (a[c-1]+1))continue;
a[c]=x;
c++;
}
}
for (Integer number : a)
{
System.out.println(number);
}
}
}
if you don't understand the last for loop , please tell , i will update it.
如果你不明白最后一个 for 循环,请告诉,我会更新它。
回答by reveance
You have to check if the number already exist, you could easily do that by putting your numbers in a List
, so you have access to the method contains
. If you insist on using an array then you could make a loop which checks if the number is already in the array.
您必须检查该号码是否已经存在,您可以通过将您的号码放入 a 来轻松做到这一点List
,这样您就可以访问该方法contains
。如果您坚持使用数组,那么您可以创建一个循环来检查该数字是否已经在数组中。
Using ArrayList:
使用ArrayList:
ArrayList numbers = new ArrayList();
while(numbers.size() < 6) {
int random = numGen(); //this is your method to return a random int
if(!numbers.contains(random))
numbers.add(random);
}
Using array:
使用数组:
int[] numbers = new int[6];
for (int i = 0; i < numbers.length; i++) {
int random = 0;
/*
* This line executes an empty while until numGen returns a number
* that is not in the array numbers yet, and assigns it to random
*/
while (contains(numbers, random = numGen()))
;
numbers[i] = random;
}
And add this method somewhere as its used in the snippet above
并将此方法添加到上面的代码段中使用的某个位置
private static boolean contains(int[] numbers, int num) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == num) {
return true;
}
}
return false;
}
回答by TheCures
you can use a boolean in a while loop to identify duplicates and regenerate
您可以在 while 循环中使用布尔值来识别重复项并重新生成
int[] array = new int[10]; // array of length 10
Random rand = new Random();
for (int i = 0 ; i < array.length ; i ++ ) {
array[i] = rand.nextInt(20)+1; // random 1-20
boolean found = true;
while (found) {
found = false;
// if we do not find true throughout the loop it will break (no duplicates)
int check = array[i]; // check for duplicate
for (int j = 0 ; j < i ; j ++) {
if ( array[j] == check ) {
found = true; // found duplicate
}
}
if (found) {
array[i] = rand.nextInt(20)+1 ; // replace
}
}
}
System.out.println(Arrays.toString(array));