In: Computer Science
Java 176
Lottery Program in Word.
Using ArrayLists to Simulate a Lottery Program
Simulate a Lottery Drawing by choosing 7 numbers at random from a pool containing 30 numbers
Each time a number is selected, it is recorded and removed from the pool
The pool values are 00 to 29 inclusive
Example Output:
Initial Pool: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
Picked: {01,06,09,19,25,26,27}
Remaining:[0,2,3,4,5,7,9,10,11,12,13,14,15,16,17,18,20,21,22,23,24,28,29]
Algorithm
Print out the remaining pool after the numbers are picked
Implementation in JAVA:
// import some neccessary classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Lottery {
// driver method
public static void main(String[] args) {
// declare arraylist initial
ArrayList<Integer> initial= new
ArrayList<Integer>();
// adding elements
for(int i=0;i<=29;i++) {
initial.add(i);
}
// printing initial
System.out.println("Initial pool : "+initial);
// declare picked arraylist
ArrayList<Integer> picked= new
ArrayList<Integer>();
// for picking 7 random elements
for(int i=0;i<7;i++) {
// call method which is defined below for generating
random numbers
int random=getRandomNumberUsingNextInt(0,29);
// check wheather it is picked earlier if yes then
generate random no. again
while(!check(initial,random)) {
random=getRandomNumberUsingNextInt(0,29);
}
// removing picked no. form initial list
for(int j=0;j<initial.size();j++) {
if(initial.get(j)==random) {
initial.remove(j);
}
}
// add random to picked list
picked.add(random);
}
// sort picked list by Collections
Collections.sort(picked);
// print picked in 2 digit format
System.out.print("Picked : {");
for(int i=0;i<picked.size();i++) {
if(i==picked.size()-1) {
System.out.print(String.format("%02d" , picked.get(i)));
}
else
System.out.print(String.format("%02d" ,
picked.get(i))+", ");
}
System.out.println("}");
// print remaining pool
System.out.println("Remaiming pool : "+initial);
}
// method for generating random no. with in range
public static int getRandomNumberUsingNextInt(int min,
int max) {
Random random = new Random();
return random.nextInt(max - min) + min;
}
// method for checking wheather num is in list or
not
public static boolean check(ArrayList<Integer>
list, int num) {
for(int i=0;i<list.size();i++)
{
if(list.get(i)==num) {
return true;
}
}
return false;
}
}
SAMPLE OUTPUTS:
1:
2:
Time complexity is high so you have to wait for a second for output
If you have any doubt regarding this question please ask me in comments
// THANK YOU:-)