Question

In: Computer Science

Lottery’s Powerball game, each ticket costs $2 and consists of two parts:--> Five distinct integers (i.e.,...

Lottery’s Powerball game, each ticket costs $2 and consists of two parts:--> Five distinct integers (i.e., no duplicates) between 1-69, inclusive • One integer (the “Powerball number”) between 1-26, inclusive. The Powerball number may or may not coincide with one of the previously chosen numbers. A ticket wins the jackpot if all five distinct numbers plus the Powerball number match the randomly drawn numbers. The matching of the five distinct numbers is done without regard to order. For example, a ticket with 54, 49, 3, 18, and 20 matches drawn numbers of 3, 54, 18, 20, and 49. In math, the set of five distinct numbers chosen by the player is known as a combination. The number of possible combinations of k items chosen from a set of n items is usually written as (pronounced “n choose k”) and is computable using this formula:   This concept should be familiar; it was discussed in an earlier lab. As mentioned then, calculating the factorials directly is not an efficient way to find n choose k. This is because the terms in (nk)! cancel some of the terms in n!, so there’s no need to compute those cancelled terms at all. A more efficient way to compute n choose k is this:      

The number of possible Powerball tickets can be computed by letting n = 69, k = 5, and multiplying the result of n choose k by 26 (the quantity of possible Powerball numbers):Number of possible tickets = 26   

plus one of m bonus numbers, we can compute the number of possible tickets like this. Number of possible tickets =   

The game settings (i.e., the values of k, n, and m above) can be chosen by the play.All of your code should be within a single class named Lottery.java.numPossibleTickets(int k, int n, int m-->This method should return the number of possible tickets in a lottery game that involves choosing k distinct integers from 1 to n (inclusive), plus one bonus integer from 1 to m (inclusive). Use equation (3) to compute this, and use the efficient technique of equation (2) when computing the value of n choose k. Because the number of tickets can be quite large, return it as a long value.getPlayerNumbers(int k, int n-->This method should get user input for k distinct integers between 1 and n (inclusive). The results should be returned in a 1D array of length k. Include input validation with loops to ensure that each input cannot be outside the range 1 to n, and also does not duplicate any previously entered value.getDrawnNumbers(int k, int n-->This method should simulate randomly drawing k distinct integers between 1 and n (inclusive). The results should be returned in a 1D array of length k. countMatches(int[] a, int[] b-->This method should return the number of elements in array a that also appear in array b. You may assume that both parameter arrays contain distinct elements. Here are some example arguments for this method and their expected return values:

a

b

Return Value

{1, 2, 3}

{3, 1}

2

{1, 2, 3}

{5, 7, -1}

0

  1. The main method should tie everything together. Call your previously written methods as necessary. Here’s a summary of what the main method should do:Get user input for how to set up the lottery game (i.e., get values for k, n, and m). Include input validation with loops to ensure that k ≥ 1, nk, and m ≥ 1.Show how many possible tickets exist for that game, and a single ticket’s chance of winning the jackpot.Get user input for t, how many tickets to buy. Include input validation with a loop to ensure that t ≥ 1.For each ticket, get user input for the k distinct numbers to play and the corresponding bonus number. Include input validation with loops to ensure that all the numbers are valid. (The distinct numbers should already be validated from the method getPlayerNumbers.)Once all tickets have been entered, simulate the lottery drawing.Find and show the “best” ticket(s). The “best” ticket is the one that matches more of the k distinct numbers than any other ticket. Matching the bonus number is used as a tiebreaker. For example, in a game that involves selecting 3 distinct numbers, here’s a hierarchy of possible tickets from best to worst:
    • All 3 numbers match, plus the bonus number (this wins the jackpot)
    • All 3 numbers match, without the bonus number
    • 2 of 3 numbers match, plus the bonus number
    • 2 of 3 numbers match, without the bonus number
    • 1 of 3 numbers match, plus the bonus number
    • 1 of 3 numbers match, without the bonus number
    • 0 of 3 numbers match, and the bonus number matches
    • 0 of 3 numbers match, and the bonus number doesn’t match In case two or more tickets tie for “best,” show all of them.
  • For the best ticket(s), show how many of the k distinct numbers match the drawn numbers, whether the bonus number matches, and whether the jackpot was won. To win the jackpot, all k distinct numbers and the bonus number must match the drawn numbers.The next pages have examples of how your completed program might look when running.Example program run (underlined parts indicate what the user enters) --> First, let’s set up the game!How many distinct numbers should the player pick? 4 OK. Each of those 4 numbers should range from 1 to what? 3Error - range must be at least 1 to 4 to have a valid game. Please try again: 4OK. And finally, the bonus number should range from 1 to what? 2-->There are 2 possible tickets in this game. Each ticket has a 50.0% chance of winning the jackpot. Let’s play, good luck!How many tickets would you like to buy? Error - must buy at least 1 ticket! Please try again: 1* Ticket #1 of 1 *Pick your 4 distinct numbers!Enter number 1 (must be 1-4, cannot repeat): 1Enter number 2 (must be 1-4, cannot repeat): 2 Enter number 3 (must be 1-4, cannot repeat): 1Error - you’ve already entered 1. Please try again.Enter number 3 (must be 1-4, cannot repeat): 3Enter number 4 (must be 1-4, cannot repeat): 1Error - you’ve already entered 1. Please try again.Enter number 4 (must be 1-4, cannot repeat):4Now pick your bonus number (must be 1-2): 3Error - number must be between 1 and 2. Please try again: 2Your tickets so far: --------------------

1               2              3              4              ||              Bonus: 2

The moment of truth has arrived! Here are the drawn numbers:

4               2              1              3              ||              Bonus: 2

Your best ticket(s):

1               2              3              4              ||              Bonus: 2

You matched 4/4 drawn numbers.You did match the bonus number.WOOHOO, JACKPOT!!

Example program run (underlined parts indicate what the user enters)First, let’s set up the game!How many distinct numbers should the player pick? 5OK. Each of those 5 numbers should range from 1 to what? 69OK. And finally, the bonus number should range from 1 to what? -1Error - range must be at least 1 to 1 to have a valid game. Please try again: 26There are 292201338 possible tickets in this game. Each ticket has a3.4222978130237034E-7% chance of winning the jackpot. Let’s play, good luck!How many tickets would you like to buy? -22Error - must buy at least 1 ticket! Please try again: 3* Ticket #1 of 3 *Pick your 5 distinct numbers!Enter number 1 (must be 1-69, cannot repeat): 77Error - number must be between 1 and 69. Please try again.Enter number 1 (must be 1-69, cannot repeat): 1Enter number 2 (must be 1-69, cannot repeat): 2Enter number 3 (must be 1-69, cannot repeat): 3Enter number 4 (must be 1-69, cannot repeat): 4Enter number 5 (must be 1-69, cannot repeat): 5Now pick your bonus number (must be 1-26): 22Your tickets so far: --------------------

1               2              3              4              5               ||              Bonus: 22

* Ticket #2 of 3 *Pick your 5 distinct numbers!Enter number 1 (must be 1-69, cannot repeat): 55Enter number 2 (must be 1-69, cannot repeat): 22Enter number 3 (must be 1-69, cannot repeat): 33Enter number 4 (must be 1-69, cannot repeat): 44Enter number 5 (must be 1-69, cannot repeat): 22Error - you’ve already entered 22. Please try again.Enter number 5 (must be 1-69, cannot repeat): 11Now pick your bonus number (must be 1-26): 19

Your tickets so far: --------------------

1               2              3              4              5               ||              Bonus: 22

55             22             33            44            11             ||              Bonus: 19

* Ticket #3 of 3 *Pick your 5 distinct numbers!Enter number 1 (must be 1-69, cannot repeat): 8Enter number 2 (must be 1-69, cannot repeat): 13 Enter number 3 (must be 1-69, cannot repeat): 2Enter number 4 (must be 1-69, cannot repeat): 17Enter number 5 (must be 1-69, cannot repeat): 29Now pick your bonus number (must be 1-26): 4

Your tickets so far: --------------------

1               2              3              4              5               ||              Bonus: 22

55        22        33        44        11        ||        Bonus: 19 8     13        2          17        29        ||        Bonus: 4

*****

The moment of truth has arrived! Here are the drawn numbers:

43            3               22            36            51             ||              Bonus: 4

Your best ticket(s):

1              2              3              4              5               ||              Bonus: 22

55            22             33            44            11             ||              Bonus: 19

You matched 1/5 drawn numbers. You did not match the bonus number.

Sorry, no jackpot this time. Really, did you expect anything else?

Try may be next time!!!!

Solutions

Expert Solution

Main.java

import java.util.Scanner;

public class Main {
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        LotteryGame game = new LotteryGame(6, 1, 49);
        System.out.println(game.getExplanationString());
        boolean run = true;
        while (run) {
            game.play();
            System.out.print("Continue (Y / N): ");
            System.out.flush();
            run = scanner.nextLine().equalsIgnoreCase("Y");
            System.out.println();
        }
    }   
}

LotteryGame.java

import java.util.Scanner;

public class LotteryGame {
    private Scanner scanner = new Scanner(System.in);

    private final int drawSize;
    private final int drawLowerLimit;
    private final int drawUpperLimit;

    public LotteryGame(int drawSize, int drawLowerLimit, int drawUpperLimit) {
        this.drawSize = drawSize;
        this.drawLowerLimit = drawLowerLimit;
        this.drawUpperLimit = drawUpperLimit;
    }

    public void play() {
        // generate new random draw
        Draw draw = Draw.generateRandomDraw(drawSize, drawLowerLimit, drawUpperLimit);

        // let the user guess
        Draw userDraw = guess();

       // compare the draws and print result
        int rightNumbers = draw.compare(userDraw);
        System.out.println("Your guess: " + userDraw.getStringRepresentation());
        System.out.println("Draw:       " + draw.getStringRepresentation());
        System.out.println("You guessed " + rightNumbers + " right!");
        System.out.println();
    }

    public Draw guess() {
        int numbers[] = new int[drawSize];
        while (true) {
            try {
                for (int i = 0; i < drawSize; i++) {
                    numbers[i] = HelpfulFunctions.saveIntInput("Number " + (i+1) + ": ");
                }
                System.out.println();
                return new Draw(numbers);
            } catch (IllegalArgumentException e) {
                System.out.println("The numbers have to be unique\n");
            }
        }
    }

    public String getExplanationString() {
        StringBuilder sb = new StringBuilder();
        sb.append("You have to guess the numbers of a lottery draw.\n");
        sb.append("A draw consists of 6 different numbers.\n");
        sb.append("Each number is in a range between 1 and 49.\n");
        sb.append("The more numbers you guess right, the luckier you can be!\n");
        return sb.toString();

}

}

HelpfulFunctions.java

import java.util.Scanner;

public class HelpfulFunctions {
    private static Scanner scanner = new Scanner(System.in);

    public static int saveIntInput(String message) {
        while (true) {
            try {
                System.out.print(message);
                System.out.flush();
                return Integer.valueOf(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Not a valid number.");
            }
        }
    }

Draw.java

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class Draw {
    public int[] numbers;

    public Draw(int[] numbers) throws IllegalArgumentException {
        // check if all numbers are unique
        for (int i = 0; i < numbers.length; i++) {
            for (int j = 0; j < numbers.length; j++) {
                if (i == j) continue;
                if (numbers[i] == numbers[j]) {
                    throw new IllegalArgumentException("All numbers have to be unique.");
                }
            }
        }

        this.numbers = numbers;
    }

    public static Draw generateRandomDraw(int numberOfEntries, int lowerLimit, int upperLimit) {
        // generate list that contains possible values
        List<Integer> possibleValues = new ArrayList<>();
        for (int i = lowerLimit; i <= upperLimit; i++) {
            possibleValues.add(i);
        }

        // fill draw with randomly picked values
        int[] numbers = new int[numberOfEntries];
        Random random = new Random();
        for (int i = 0; i < numberOfEntries; i++) {
            int randomIndex = random.nextInt(possibleValues.size());
            Integer pickedValue = possibleValues.get(randomIndex);
            possibleValues.remove(pickedValue);
            numbers[i] = pickedValue;
        }

        Arrays.sort(numbers);

        return new Draw(numbers);
    }
    // returns count of equal numbers
    public int compare(Draw draw) throws IllegalArgumentException {
        if (draw.numbers.length != numbers.length) {
            throw new IllegalArgumentException("The draws dont have the same length.");
        }

        int count = 0;
        for (int i = 0; i < numbers.length; i++) {
            for (int j = 0; j < numbers.length; j++) {
                if (numbers[i] == draw.numbers[j]) {
                    count++;
                }
            }
        }

        return count;
    }

    public String getStringRepresentation() {
        StringBuilder sb = new StringBuilder();
        sb.append("[" + numbers[0]);
        for (int i = 1; i < numbers.length; i++) {
            sb.append(", " + numbers[i]);
        }
        sb.append("]");
        return sb.toString();
    }
}

Related Solutions

To play the PowerBall lottery, you buy a ticket that has five unique numbers in the...
To play the PowerBall lottery, you buy a ticket that has five unique numbers in the range of 1–69, and a “PowerBall” number in the range of 1–26. (You can pick the numbers yourself, or you can let the ticket machine randomly pick them for you.) Then, on a specified date, a winning set of numbers is randomly selected by a machine. If your first five numbers match the first five winning numbers in any order, and your PowerBall number...
Show that for any k ≥ 2, if n + 1 distinct integers are chosen from...
Show that for any k ≥ 2, if n + 1 distinct integers are chosen from the set [kn] = {1, 2, . . . , kn}, then there will be two integers which differ by at most k − 1. Please demonstrate the steps so that I can learn from it and solve other problems by following the reasoning!
A graph consists of nodes and edges. An edge is an (unordered) pair of two distinct...
A graph consists of nodes and edges. An edge is an (unordered) pair of two distinct nodes in the graph. We create a new empty graph from the class Graph. We use the add_node method to add a single node and the add_nodes method to add multiple nodes. Nodes are identified by unique symbols. We call add_edge with two nodes to add an edge between a pair of nodes belonging to the graph. We can also ask a graph for...
A graph consists of nodes and edges. An edge is an (unordered) pair of two distinct...
A graph consists of nodes and edges. An edge is an (unordered) pair of two distinct nodes in the graph. We create a new empty graph from the class Graph. We use the add_node method to add a single node and the add_nodes method to add multiple nodes. Nodes are identified by unique symbols. We call add_edge with two nodes to add an edge between a pair of nodes belonging to the graph. We can also ask a graph for...
Genes can generally be described as having two distinct parts. What are they?
Genes can generally be described as having two distinct parts. What are they?
Choose and write down a sample of 12 distinct (different) positive integers (no modes), each less...
Choose and write down a sample of 12 distinct (different) positive integers (no modes), each less than 100, in a way that your data set would have a range of 90, a mean of 59, and a median of 55 In order not to treat the data as an abstract set, state what your data might represent with an applicable unit. Show your data set and your work to demonstrate that your data set does have the statistical characteristics mentioned....
The carbon content (in parts per million) was measured five times for each of two different...
The carbon content (in parts per million) was measured five times for each of two different silicon wafers. The measurements were as follows. [3 Points] Wafer A : 1.12 1.15 1.16 1.10 1.13 Wafer B : 1.21 1.18 1.15 1.18 1.14 Construct a 90% confidence interval for the difference in carbon content between the two wafers. `Assume that the populations are normally distributed and the population variances are equal.
14 randomly chosen students have each won a free ticket to play a game of chance....
14 randomly chosen students have each won a free ticket to play a game of chance. In this game a wheel is spun that has been equally divided among 20 values, and when the wheel stops spinning a pointer will have selected one of the 20 values randomly (think Wheel-of-Fortune style). So therefore we will assume that each of the 20 outcomes is equally likely. Before spinning, the player chooses which value they think it will stop on. If it...
A game of chance offers the following odds and payoffs. Each play of the game costs...
A game of chance offers the following odds and payoffs. Each play of the game costs $100, so the net profit per play is the payoff less $100. Probability Payoff Net Profit 0.10 $700 $600 0.50 100 0 0.40 0 –100 a-1. What is the expected cash payoff? (Round your answer to the nearest whole dollar amount.) a-2. What is the expected rate of return? (Enter your answer as a percent rounded to the nearest whole number.) b-1. What is...
2. You’re playing a game of Magic: The Gathering with a deck that consists of 60...
2. You’re playing a game of Magic: The Gathering with a deck that consists of 60 cards, 24 of which are land cards. You draw an opening hand of seven cards which contains exactly one land and six non-lands. (For this problem, you are welcome to read and use the tools of this article1, but your answers must include clear explanations of the mathematical reasoning you’re using!) (a) What is the probability of this event (that your hand of seven...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT