In: Computer Science
Java:
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
CODE -
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class lottry
{
public static void main(String[] args)
{
Random rand = new Random();
// Creating two ArrayLists of type Integer called pool and pick
ArrayList<Integer> pool = new ArrayList<Integer>();
ArrayList<Integer> pick = new ArrayList<Integer>();
// Adding elements to the pool ArrayList
for(int i=0; i<30; i++)
pool.add(i);
// Displaying the initial pool ArrayList
System.out.print("Initial Pool: [" + pool.get(0));
for(int i=1; i<30; i++)
System.out.print(", " + pool.get(i));
System.out.println("]");
int i=0;
// Choosing 7 random numbers
while(i<7)
{
boolean found = false;
int num = rand.nextInt(30);
// Loop to check if random number generated is already in the ArrayList pick so that the numbers don't get repeated.
for (int j=0; j<i; j++)
{
if(pick.get(j) == num)
found = true;
}
// Adding the choosen number to pool ArrayList and removing the number from the pool ArrayList
if(!found)
{
pick.add(num);
for(int j=0; j<30-i-1; j++)
if(pool.get(j) == num)
pool.remove(j);
i++;
}
}
// Sorting the pick ArrayList
Collections.sort(pick);
// Displaying the picked numbers
System.out.printf("Picked: {%02d", pick.get(0));
for (i=1; i<7; i++)
System.out.printf(", %02d", pick.get(i));
System.out.println("}");
// Displaying the remaining pool ArrayList
System.out.print("Remaining: [" + pool.get(0));
for(i=1; i<23; i++)
System.out.print(", " + pool.get(i));
System.out.println("]");
}
}
SCREENSHOTS -
CODE -
OUTPUT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.