Reputation: 79
public class LotteryNumbers {
private ArrayList <Integer> numbers;
public LotteryNumbers() {
this.numbers = new ArrayList <Integer> ();
this.drawNumbers();
}
public ArrayList <Integer> numbers() {
return this.numbers;
}
public void drawNumbers() {
Random random = new Random ();
int counter = 0;
while (counter < 7) {
this.numbers.add(random.nextInt(39) + 1);
counter++;
}
}
This is a class used for printing 7 numbers from 1..39.
It does that job but the problem is I want the 7 random numbers to be different.
How do I check if an arrayList contains the same number since it is random?
Thanks for reading.
Upvotes: 0
Views: 1079
Reputation: 1955
You could also put your numbers in a list and use COllections.shuffle and get the first 7 occurences.
You do not need to check if duplicate...
ArrayList list = new ArrayList(); list.add(1); list.add(2); ....
Collections.shuffle(list);
loop and get your numbers...
int num = Integer.intValue(list.get(i));
Upvotes: 0
Reputation: 592
You could use contains as as the earlier responses suggest, however contains on an array list in inefficient with O(n)
complexity. One of the comments by @TheLostMind suggest using a Set, the best Set implementation to use in this instance is BitSet
, note it does not confirm to the java.util.Set
interface specification.
public class LotteryNumbers {
private final int[] numbers = new int[7]
public LotteryNumbers() {
this.drawNumbers();
}
public int[] numbers() {
return this.numbers;
}
public void drawNumbers() {
BitSet selected = new BitSet(40);
Random random = new Random ();
int counter = 0;
while (counter < 7) {
int num = random.nextInt(39) + 1;
if(!selected.get(num)) {
selected.flip(num);
numbers[counter++] = num;
}
}
}
This implementation, tho unlikely, does not guarantee that you will always get a result.
Upvotes: 0
Reputation: 2899
How do I check if an ArrayList contains the same number since it is random?
Like this (example):
public void drawNumbers() {
Random random = new Random ();
int counter = 0;
while (counter < 7) {
int newNumber = random.nextInt(39) + 1;
if (! numbers.contains(newNumber)) {
this.numbers.add(newNumber);
counter++;
}
}
}
Upvotes: 2
Reputation: 34176
You could try using the contains()
method from the ArrayList numbers
:
public void drawNumbers()
{
Random random = new Random();
int counter = 0;
int choice;
while (counter < 7) {
choice = random.nextInt(39) + 1;
if (numbers.contains(choice)) {
continue;
}
numbers.add(choice);
counter++;
}
}
From Java Docs:
public boolean contains(Object o): Returns true if this list contains the specified element.
So, if the ArrayList
already contains the choice
(randomly generated), it will continue to the next iteration (counter
won't be increased) and choose another random number. If it doesn't contains the choice
, it will add it to the array and increase counter
.
This can also be done by this way (without using continue
)
if (!numbers.contains(choice)) {
numbers.add(choice);
counter++;
}
Upvotes: 3