Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created November 19, 2012 21:06
Show Gist options
  • Save DominicFinn/4113899 to your computer and use it in GitHub Desktop.
Save DominicFinn/4113899 to your computer and use it in GitHub Desktop.
Lottery numbers
package lotterynumbergenerator;
import java.util.Arrays;
import java.util.Random;
public class LotteryNumberGenerator {
public static void main(String[] args) {
//an array to keep track of the numbers that have been created
int[] numbers = new int[6];
for(int i = 0; i <6; i++) {
numbers[i] = randomNumber(numbers);
System.out.println(numbers[i]);
}
}
///Creates a random distinct number
private static int randomNumber(int[] currentNumbers) {
Random rand = new Random();
int number = 0;
Boolean distinct = false;
//sort the current numbers, this is needed for a binary search
Arrays.sort(currentNumbers);
//generate random numbers until a number is found that isn't in the array
while(!distinct) {
number = rand.nextInt(50);
//check the array of numbers made already and make sure the new
//random number is distinct
if(Arrays.binarySearch(currentNumbers, number) <= 0) {
distinct = true;
}
}
return number;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment