2

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.

9
  • My first thought on this is that if you want real random numbers, you should allow for repetition. If you generate a random number and then check for clauses, discard it and, say, generate another random number, the resulting array will not contain completely random numbers. Commented Jan 22, 2014 at 12:40
  • 1
    You could add the generated numbers in a Set (which automatically removes duplicates), until the size() of the Set is 6, and then convert the Set to an array using toArray(). Commented Jan 22, 2014 at 12:41
  • @EricTobias what do you mean check for clauses? Commented Jan 22, 2014 at 12:58
  • @sp00m I dont know what is that Set thing. Im sorry. Commented Jan 22, 2014 at 12:58
  • A clause is a logical statement. So checking whether your data structure already contains the same random number would be a clause. Commented Jan 22, 2014 at 13:02

7 Answers 7

8

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.

Sign up to request clarification or add additional context in comments.

7 Comments

i think he is asking for unique random number in your case you are giving him no from 1 to 7
@IndraYadav: he clearly gave an example with numbers from 1 to 6 but I'll edit my answer to reflect both cases.
@IndraYadav: edited to allow generation of numbers either in sequence or not, using the same "one for loop, one shuffle" solution.
@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?
@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.
|
1

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

2 Comments

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 I updated the post with an example of an array too. Hope it's useful now
0

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

2 Comments

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.
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.
0

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

Comments

0

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

Comments

-1

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.

1 Comment

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. :(
-1

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)

2 Comments

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.
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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.