JAVA数组中的非重复随机数

JAVA数组中的非重复随机数,java,arrays,random,Java,Arrays,Random,我想在一个数组中生成6个数字,同时对其进行比较,这样它就不会是相同的或没有重复的数字。例如,我想以任意顺序生成1-2-3-4-5-6,最重要的是不重复。所以我的想法是,在生成的数组中逐个比较当前数组,如果该数字重复,它将重新运行该方法并再次随机化一个数字,以避免重复数字 这是我的密码: import javax.swing.*; public class NonRepeat { public static void main(String args[]) { in

我想在一个数组中生成6个数字,同时对其进行比较,这样它就不会是相同的或没有重复的数字。例如,我想以任意顺序生成1-2-3-4-5-6,最重要的是不重复。所以我的想法是,在生成的数组中逐个比较当前数组,如果该数字重复,它将重新运行该方法并再次随机化一个数字,以避免重复数字

这是我的密码:

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;
    }
}
import javax.swing.*;
公共类不重复
{
公共静态void main(字符串参数[])
{
int数组[]=新的int[6];
int login=Integer.parseInt(JOptionPane.showInputDialog(“ASD”);
while(登录名!=0)
{
字符串输出=”;

对于(int index=0;index使用
List
而不是数组和
List#contains
来检查数字是否重复。

您可以从1到6生成数字(另一种解决方案见下文),然后执行
集合。shuffle
来洗牌您的数字

    final List<Integer> l = new ArrayList<Integer>();
    for (int j = 1; j < 7; j++ ) {
        l.add( j );
    }
    Collections.shuffle( l );
请注意,通过将
r.nextInt(42)
更改为
r.nextInt(1)
,可以有效地将非重复数字从1更改为6。

使用列表和.contains(Object obj)方法。 所以,您可以验证列表之前是否添加了随机数

更新-基于你在随机循环中可能损失的时间

    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);
    }
List List=new ArrayList();
int x=1;
而(x<7){
增加(x);
x++;
}
集合。洗牌(列表);
用于(整数:列表){
系统输出打印项次(编号);
}

您可以使用
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);
        }
    }
}
import java.util.*;
公共类随机数
{
公共静态void main(字符串[]args)
{
随机abc=新随机();
int[]a=新的int[6];
整数极限=100,c=0;
int-chk=0;
布尔y=真;
对于(;c<6;)
{
int x=abc.nextInt(限制+1);

对于(int i=0;i您必须检查该数字是否已经存在,您可以通过将您的数字放入
列表
,轻松做到这一点,这样您就可以访问
包含的方法
。如果您坚持使用数组,则可以循环检查该数字是否已经在数组中

使用:

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);
}
    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;
    }
ArrayList number=new ArrayList();
while(number.size()<6){
int random=numGen();//这是返回随机int的方法
如果(!number.contains(随机))
数字。添加(随机);
}
使用数组:

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);
}
    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;
    }
int[]数字=新的int[6];
for(int i=0;i
并将此方法添加到上面代码段中使用的某个位置

private static boolean contains(int[] numbers, int num) {
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] == num) {
            return true;
        }
    }
    return false;
}
私有静态布尔包含(int[]个数字,int num){
for(int i=0;i
以下是根据您的代码提供的解决方案-

您只需更改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;
}
publicstaticintnumgen(int数组[])
{
int random=(int)(1+Math.random()*6);

对于(int loop=0;loop,可以在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));
int[]数组=新的int[10];//长度为10的数组
Random rand=新的Random();
for(int i=0;i
我的第一个想法是,如果你想要真正的随机数,你应该允许重复。如果你生成一个随机数,然后检查子句,放弃它,然后生成另一个随机数,那么生成的数组将不会包含完全随机数。你可以将生成的数添加到
集合中
(自动删除重复项),直到
集合的
size()
6
,然后使用
toArray()将
集合转换为数组
@EricTobias你说检查子句是什么意思?@sp00m我不知道那是什么。对不起,子句是一个逻辑语句。所以检查你的数据结构是否已经包含相同的随机数就是一个子句。我想他要求的是唯一的随机数。在你的情况下,你给他从1到0的否定7@IndraYadav字体他arly给出了一个数字从1到6的示例,但我将编辑我的答案以反映这两种情况。@IndraYadav:编辑以允许按顺序或不按顺序生成数字,使用相同的“一个循环,一个洗牌”解决方案。@TacticalCoder我不知道这段代码是如何工作的,但我正在尝试。很抱歉。但是如果速度太慢,如果我将1-6改为1-42会怎么样?@lazygeniusLANZ:生成一个包含42个数字的列表?速度会非常快。在我的系统上,使用第二个解决方案生成一个包含100000个数字的列表需要25毫秒……我建议的解决方案是O(n)在复杂性和现代CPU上做比尔
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));