Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random Numbers , but it must be Generated with Unique numbers without replications

Tags:

java

random

int[] drawNumbers = new int[10];//Array With 10 Random Numbers USED for DRAWN NUMBERS
String x = "Drawn Numbers: ";
List<Ticket> ticketWon ;

do{
    //GENERATING 10 Random Numbers
    for (int i = 0; i <= drawNumbers.length -1 ; i++) {
           Random r = new Random();
           drawNumbers[i] = r.nextInt(99) + 1;
           x += drawNumbers[i] + " ";
    }
}

I'm trying to generate 10 random numbers that must be random generated and Unique. My problem is that with Random r = new Random() there are times that replicated numbers are shown. How can i generate 10 random numbers from range 1 to 99 without replications?

Problem is for a Lottery System

I would like to use Collection.Shuffle but I'm not that sure how it should be implemented.

like image 883
user3681327 Avatar asked Feb 10 '23 23:02

user3681327


2 Answers

Here is an alternative way to achieve your desired result. We populate a list with values 1 to 99. Then we shuffle the list and grab the first 10 values:

public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    for (int i=1; i<100; i++) {
        list.add(new Integer(i));
    }
    Collections.shuffle(list);
    for (int i=0; i<10; i++) {
        System.out.println(list.get(i));
    }
}

You won't have to import/directly deal with Random, which is a plus. However, as pointed out by @Voicu (in the comments), shuffle does indeed utilize random:

public static void shuffle(List<?> list) {
    if (r == null) { 
        r = new Random();
    }
    shuffle(list, r);
}
private static Random r;
like image 124
benscabbia Avatar answered Feb 13 '23 14:02

benscabbia


You can broadly think of this problem as having a deck of cards numbered from 1 to 99, and you want to pick 10 of those cards. The solution would be to, programmatically, create that deck and then randomly select from that deck and remove from the deck.

We can model the deck as a List of Integers and populate that List with entries from 1 to 99 with something like this:

List<Integer> deck = new ArrayList<Integer>();
for( int i=1; i<=99; i++ ){
  deck.add( i );
}

We then need to pick a random card between the 0th card (lists are numbered starting at 0) and the number of elements in the list:

int draw = r.nextRandom( deck.size() );
Integer card = deck.remove( draw );

And repeat that 10 times, doing something with the "card" (say, putting it into an array, or another list, or whatever:

int drawNumbers = new int[10];
for( int co=0; co<10; co++ ){
  int draw = r.nextRandom( deck.size() );
  Integer card = deck.remove( draw );
  drawNumbers[co] = card;
}
like image 36
Prisoner Avatar answered Feb 13 '23 13:02

Prisoner