+1 (315) 557-6473 

Mathematical Assignment Solution in Java


Question:

Pick a positive integer to get help with java assignment. Then repeatedly apply this (rather silly) process:

  • If your number is even, divide it by 2, and the result becomes your new number.
  • If your number is odd, multiply it by 3, and add 1; that result becomes your new number.
  • Repeat this process until the result is the number 1.

Why stop when the number is 1? Because once you get to 1, you enter a loop. Try it: 1 -> 4 -> 2 -> 1 -> 4 ->... Hopefully, you get the idea.

Your program will interact with a human user via keyboard input and screen output. When the program starts, your program should print out a short explanation of the process described above. Then your program should give the interactive user three choices:

  • designate a number to start the process
  • designate a range of numbers to use with the process
  • quit the program

If the user decides to quit the program, exit with a pleasant message. If necessary, wait for the user to press ENTER to allow the user to see your "goodbye" message.

If the user designates a number to start the process, execute the process until the number becomes 1. Figure out a method to gracefully display the entire action (each number generated), and finish with the number of steps it took to get to 1. (Don't count the starting number from the user, and do count the 1 when you reach it.) If someone puts in a 1, then the program should say there were 3 steps (please see above). Wait for the user to push ENTER before moving on.

If the user wants to designate a range of numbers, then prompt for the smaller number, and prompt for the larger number. I'll call the smaller number S and the larger number L. When you have both those numbers, then run the process for all of the numbers from S to L, inclusive, one at a time. For each of the numbers, keep track of the shortest run (until 1), the longest run, and the average length of a run. When your program has done all the required processes, report the findings to the screen. Again, wait for the user to press ENTER to move on.

Whenever you prompt the user for input, give clear directions on what inputs are legal. If the user enters illegal input, tell the user what went wrong, and prompt. Keep going until the user enters a legal input.

Whenever you give output, use clear language and decent, readable formatting.

If the user chooses to quit, you stop. If the user chooses either of the other two choices, you keep going, by again giving the user the three choices.

Solution:

Explanation:

        This program will simulate a pill-taking procedure from a jar full of pills

        The program will randomly pick only pill, and if the pill is a whole pill,

        it will be cut in half and then one of the halves is returned to the jar,

        but if the pill take is half-pill, then it is just removed from the jar

        The idea of this program is to prove that, for N pills, the jar will be empty after 2*N days

        The program will ask the user for a positive integer less or equal than 1000, representing ...

        ... the number of pills.

        Then, it will be for another positive integer less than or equal to 1000, representing...

        ... the number of simulations to be performed.

        The integers will be read using the Scanner class and using a try-catch block to check

        that the input entered by the users is indeed an integer and not a string, char, etc.

        If the user enters an invalid input (not an integer, or integer less than 1 or higher than 1000) ...

        then the program will display an error message and re-prompt

        The jar is represented by a List of Integer, and the pills are represented by integers

        If the integer inside the list is 1, then it is a whole pill

        If the integer inside the list is 2, then it is a half-pill

        The jar (List) begins filled with N ones, and then as the simulation run, for each day,

        if the randomly selected pill is a whole pill, then a number 1 is removed from the list, and a number 2

        is added. This represents taking the whole pill, splitting it in half, and then returning one half to the jar

        If the randomly selected pill is a half-pill (a number 2) then it is just removed from the jar

        Note that, the pill (random index of the element in the list) is randomly selected using the class ...

        ... Random and the method nextInt(n) where n is the size of the List (number of pills in the jar)

    External files: None


*/ import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; public class Main { static List fillBottle(int N) { // Create a List of integers List bottle = new ArrayList(); // the number 1 represents whole pills, while 2 represents half pills // so fill the bottle with 1 for(int i = 0; i < N; i++) bottle.add(1); return bottle; } public static void main(String[] args) { // create Scanner Scanner sc = new Scanner(System.in); // Create random object Random r = new Random(); int N, S; while(true) { try { // ask for N System.out.print("Enter the number of pills: "); N = Integer.valueOf(sc.nextLine()); if(N < 1 ||N > 1000) { System.out.println("The number of pills must be a positive integer equal or smaller than 1000."); } else break; } catch(Exception ex) { System.out.println("Please enter a valid positive integer equal or smaller than 1000."); } } while(true) { try { // ask for S System.out.print("Enter the number of simulations: "); S = Integer.valueOf(sc.nextLine()); if(S < 1 ||S > 1000) { System.out.println("The number of simulations must be a positive integer equal or smaller than 1000."); } else break; } catch(Exception ex) { System.out.println("Please enter a valid positive integer equal or smaller than 1000."); } } // The following variable are used to store the averages double[] average_whole = new double[2*N]; double[] average_half = new double[2*N]; double[] average_ratio = new double[2*N]; // Initialize arrays with zeros for(int i = 0; i < 2*N; i++) { average_whole[i] = 0.0; average_half[i] = 0.0; average_ratio[i] = 0.0; } // now, prepare simulations int index; for(int s = 1; s <= S; s++) { // initialize number of whole and half pills int n_whole = N; int n_half = 0; List pills = fillBottle(N); System.out.println("Simulation number " + s); System.out.println(String.format("| %5s | %-8s | %-8s | %-8s |", "---", "---------", "--------", "-----")); System.out.println(String.format("| %5s | %-8s | %-8s | %-8s |", "Day", "No. Whole", "No. Half", "Ratio")); System.out.println(String.format("| %5s | %-8s | %-8s | %-8s |", "---", "---------", "--------", "-----")); for(int day = 1; day <= 2*N; day++) { // count whole pills n_whole = 0; n_half = 0; for(int i = 0; i < pills.size(); i++) { if(pills.get(i) == 1) n_whole++; else n_half++; } // Calculate the ratio double ratio = (double)n_half / (double)(n_whole + n_half); System.out.println(String.format("| %5d | %-9d | %-8d | %-8.2f |", day, n_whole, n_half, ratio)); // store numbers in arrays for average values average_whole[day-1] += (double)n_whole/(double)(S); average_half[day-1] += (double)n_half/(double)(S); average_ratio[day-1] += (double)ratio/(double)(S); // Now simulate picking a pill index = r.nextInt(pills.size()); if(pills.get(index) == 1) // taking a whole, so we must insert a half-pill { pills.remove(index); pills.add(2); } else // take half pills.remove(index); } System.out.println(""); } // Now print average values for each day System.out.println(""); System.out.println("Average of values"); System.out.println(String.format("| %5s | %-20s | %-20s | %-10s |", "---", "-------------------------", "------------------------", "----------")); System.out.println(String.format("| %5s | %-10s | %-10s | %-10s |", "Day", "Avg. Count of Whole Pills", "Avg. Count of Half Pills", "Avg. Ratio")); System.out.println(String.format("| %5s | %-20s | %-20s | %-10s |", "---", "-------------------------", "------------------------", "----------")); for(int day = 1; day <= 2*N; day++) { System.out.println(String.format("| %5d | %-25.2f | %-24.2f | %-10.2f |", day, average_whole[day-1], average_half[day-1], average_ratio[day-1])); } // wait for user press ENTER to exit System.out.println(""); System.out.println("Press enter to exit..."); sc.nextLine(); sc.close(); } }