Non-repeating random numbers inside array JAVA

13,021

Solution 1

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;
    }
}

Solution 2

You can generate numbers from, say, 1 to 6 (see below for another solution) then do a Collections.shuffle to shuffle your numbers.

    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.

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.

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.

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.

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.

EDIT It'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:

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.

Solution 3

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;
}
Share:
13,021
lazygeniusLANZ
Author by

lazygeniusLANZ

Updated on June 04, 2022

Comments

  • lazygeniusLANZ
    lazygeniusLANZ almost 2 years

    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.

  • Indra Yadav
    Indra Yadav over 10 years
    i think he is asking for unique random number in your case you are giving him no from 1 to 7
  • TacticalCoder
    TacticalCoder over 10 years
    @IndraYadav: he clearly gave an example with numbers from 1 to 6 but I'll edit my answer to reflect both cases.
  • TacticalCoder
    TacticalCoder over 10 years
    @IndraYadav: edited to allow generation of numbers either in sequence or not, using the same "one for loop, one shuffle" solution.
  • lazygeniusLANZ
    lazygeniusLANZ over 10 years
    @TacticalCoder I dont know how this code works, but Im trying. Im sorry. But if it will be slow, what if I change 1-6 to 1-42?
  • Eric Tobias
    Eric Tobias over 10 years
    The thing about randomness is that it is random! Your while might not terminate in your lifetime. While improbable, it is possible. I would avoid this practice and recommend writing code where the time complexity can be calculated with certainty.
  • TacticalCoder
    TacticalCoder over 10 years
    @lazygeniusLANZ: generating a list of 42 numbers? It's going to be very fast. Generating a list of 100 000 numbers using the second solution takes 25 milliseconds on my system... The solution I suggested are O(n) in complexity and on modern CPUs doing billions of operations per second, it's really fast. Hope it helps.
  • lazygeniusLANZ
    lazygeniusLANZ over 10 years
    I want to use an array because its our main lesson now. I did a loop thing inside the first for loop but it just dont work.
  • lazygeniusLANZ
    lazygeniusLANZ over 10 years
    Originally I want to generate numbers from 1-42 but our professors check it by using 1-6 for him to ensure that nothing will repeat. And honestly, I dont understand most of your code. I only know basics. :(
  • lazygeniusLANZ
    lazygeniusLANZ over 10 years
    @TacticalCoder I dont really care if the sequence of numbers 1-6 is in order or not. I just need it to be free from repeated numbers. Btw, I just understand some of the code. Im sorry I only know basics.
  • lazygeniusLANZ
    lazygeniusLANZ over 10 years
    I dont even know why this is down voted but this really solved and answered my question with the most easiest code which I understand.
  • TacticalCoder
    TacticalCoder over 10 years
    @lazygeniusLANZ: then the first solution is only three lines of code. The idea is really simple: first you generate non-repeating, incrementing (consecutive or not, apparently it doesn't matter), numbers. Then you simply shuffle or "randomize" your list of numbers. I'll edit the question a bit more.
  • xild
    xild over 10 years
    You're right and this why shuffle is a cool thing to do. If you think in a big cenario this is bad. I just posted a different example for our mate ;)
  • reveance
    reveance over 10 years
    @lazygeniusLANZ I updated the post with an example of an array too. Hope it's useful now
  • EpicPandaForce
    EpicPandaForce almost 10 years
    Recursion? Seriously? Why? There is no need for recursion. All you need to solve this is initialize an array with the numbers and randomly swapping the elements N times.