Created
November 19, 2012 21:06
-
-
Save DominicFinn/4113899 to your computer and use it in GitHub Desktop.
Lottery numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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