Non-repeating random numbers inside array JAVA

2019-05-19 17:34发布

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.

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.

Btw, Im new in codes so please I just want to compare it using for loop or while loop and if else.

7条回答
The star\"
2楼-- · 2019-05-19 17:40

Use List instead of array and List#contains to check if number is repeated.

查看更多
成全新的幸福
3楼-- · 2019-05-19 17:46

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.

Using 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;
}
查看更多
迷人小祖宗
4楼-- · 2019-05-19 17:48

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:

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.

查看更多
戒情不戒烟
5楼-- · 2019-05-19 17:54

Use List and .contains(Object obj) method. So you can verify if list has the random number add before.

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)

查看更多
来,给爷笑一个
6楼-- · 2019-05-19 17:57

Here is the solution according to your code -

You just need to change the numGen method -

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;
    }
}
查看更多
放荡不羁爱自由
7楼-- · 2019-05-19 17:57

you can use a boolean in a while loop to identify duplicates and regenerate

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));
查看更多
登录 后发表回答