-2

I want to generate 6 different random numbers by using Math.random and store all of them into an array. How can I make sure that they are different? I only have this so far and this has a bug. I only need numbers between 1 and 49. ( 1 + (int) (Math.random() * 49) ).

public static void main (String []args) {
    int []randomNumArray = new int [6];
    randomNumArray[0] = randomNumber();
    System.out.println(randomNumArray[0]);

    for (int i = 1; i < 6; i++) {                   
        for (int j = 0; j < i; j++) {              
            randomNumArray[i] = randomNumber();
            do {
                if (randomNumArray[i] == randomNumArray[j]) {
                    randomNumArray[i] = randomNumber();
                }
            } while(randomNumArray[i] == randomNumArray[j]);
        }
        System.out.println(randomNumArray[i]);
    }
}

//This method is for generating random numbers
public static int randomNumber (){
    return  ( 1 + (int) (Math.random() * 49) );
}
Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
coding
  • 141
  • 2
  • 4
  • 11
  • 1
    You mentioned that your code has a bug. How exactly does it manifest itself? – merlin2011 Mar 24 '14 at 03:37
  • shuffling an array is a good way to get non-repeating elements. Why don't you want to use that? – Thilo Mar 24 '14 at 03:37
  • When I run this code, the array still has duplication @merlin2011 – coding Mar 24 '14 at 03:45
  • Should have just edited this question instead of starting a new one: http://stackoverflow.com/questions/22584244/how-to-generate-6-different-random-numbers-in-java – Nico Mar 24 '14 at 03:49

2 Answers2

3

Generate random numbers and keep adding them to a Set until its size = 6. A set can contain only unique elements. So, you are assured uniqueness.

EDIT :

public static void main(String[] args)  {
        Set<Integer> intSet = new LinkedHashSet<Integer>();
        Random r = new Random();
        while (intSet.size() <= 6) {
            intSet.add(r.nextInt(49)); // or your method of generating random numbers
        }
        System.out.println(intSet);
    }
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • 4
    This works especially well if the number you want (6) is much smaller than the possible options (49). If they are close, it will perform poorly as it becomes harder to draw "new numbers". – Thilo Mar 24 '14 at 03:40
  • @Thilo - Yes. I agree. Is there an efficient way to assure/enforce uniqueness? – TheLostMind Mar 24 '14 at 03:44
  • shuffling the array is the other good approach. – Thilo Mar 24 '14 at 03:45
  • 2
    It depends on performance requirements. Even generating 48 unique numbers between 1 and 49 takes a negligible amount of time for many applications. By the way, I suggest a `LinkedHashSet` if you want to maintain a nice randomly generated order. – Jason C Mar 24 '14 at 03:46
  • @WhoAmI Can you show me how? I kinda don't get it... – coding Mar 24 '14 at 03:46
  • The cost is in generating many random numbers in order to get 48 unique ones out of 49 possibilities since only 2/49 of the numbers generated will be acceptable for the last one. Shuffling an array is an efficient solution. *Also* one should call http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int) to get a bounded random integer. *Effective Java* item 47 explains many subtle problems that are taken care of by calling `nextInt(int)`. – Jerry101 Mar 24 '14 at 03:48
  • @coding `while (size of set < count) { insert random number into set }`, where the set is, e.g., a `LinkedHashSet`, or, say, a `TreeSet` if you want the random numbers in sorted order. – Jason C Mar 24 '14 at 03:50
0

Obviously, the set approach and shuffling the array are more efficient approaches, but given the context, here is a modification of the OP's code to achieve uniqueness, to address the "bug" in his code.

import java.util.*;

public class Main {
    public static void main (String []args) {

        int []randomNumArray = new int [6];

        randomNumArray[0] = randomNumber();

        System.out.println(randomNumArray[0]);


        for (int i = 1; i < 6; i++)
        {                   
            int candidate;
            boolean foundMatch;
            do
            {
                candidate = randomNumber();
                foundMatch = false;
                for (int j = 0; j < i; j++)
                    if (candidate == randomNumArray[j])
                        foundMatch = true;
            } while (foundMatch);
            randomNumArray[i] = candidate;

            System.out.println(randomNumArray[i]);
        }
    }
    //This method is for generating random numbers
    public static int randomNumber (){
        return  ( 1 + (int) (Math.random() * 49) );
    }
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329