Author Archives: graceliana@gmail.com

Conditionals: Gambler: Modified Version

 

Modify Gambler.java to take an extra command line parameter that specifies the number of bets the gambler is willing to make so that there are three possible ways for the game to end:
* the gambler wins, loses, or runs “out of time” meaning the gambler gives up.
* Add to the output to give the expected amount of money the gambler will have when the game ends.

Think of the different outcomes and how would report on them. That means what your output would look like and how you would display it. Look back to the format of the previous gambler’s ruin activity.

A random(get it?) example:

stake: $5 goal: $10 trials: 10 games and run out of time is 7 bets

1 game – lost all your money
2 game – won
3 game – end by the 7th bet and you had $6
4 game – lost all your money
5 game – end by the 7th bet and you had $4
6 game – lost all your money
7 game – won
8 game – end by the 7th bet and you had $2
9 game – won
10 game – lost all your money

6 + 4 + 2 = 12 total accumulated from “run out of time”
the expected amount of money from 10 games is 12/3 = $4

Lesson slides on page 28

public class Gambler
{
    public static void main(String[] args)
   {
     int stake = Integer.parseInt(args[0]);
     int goal = Integer.parseInt(args[1]);
     int trials = Integer.parseInt(args[2]);

    int wins = 0;
    for (int i = 0; i < trials; i++)
     {
       int t = stake;
       while (t > 0 && t < goal)
        {
            if (Math.random() < 0.5) t++;
            else t--;
        }
        if (t == goal) wins++;
     }
   StdOut.println(wins + " wins of " + trials);  
   }
}

Conditionals: Gambler: Chart

WARNING: your program should run only once and produce this chart:
a. Modify the original gambler to show how the increase of “trials” affects the probability of winning.

A good easy format:
stake = 5 goal = 25

Trials Wins Probability
100 15%
1000 19%
10000 22%
100000 20%
1000000 20%

WARNING: your program should run only once and produce this chart:
b. Modify the original gambler to show how the increase of the “stake” affects the probability of winning.

A good easy format:
goal = 25 trials = 1000

Stake Wins Probability
5 17%
10 39%
15
20

WARNING: your program should run only once and produce this chart:
c. Modify the original gambler to show how the increase of the “goal” affects the probability of winning.

A good easy format:
stake = 5 trials = 1000

Goal Wins Probability
5 98%
10 50%
15
20
25

Conditionals: Project Euler: Sum Square Difference

Sum square difference

Problem 6

The sum of the squares of the first ten natural numbers is,

12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

/** the correct output  is 25164150 **/

Conditionals: Gambler: Questions

From page 28 on this pdf:
1. What is the “if (t == goal) wins++; ” keeping track of?
2. What does the outer loop control?
3. What happens at each trial?
4. What is the identifier “win” for?
5. What is the “stake” for?
6. What is the “goal” for?
7. How many trials would produce a good result?
8. How do you read the output in plain English?
% java Gambler 5 25 1000
203 wins of 1000

  1. If you were running this program to find the probability of winning in this game, what would need to be done to come up with the best approximation to the actual value?

a. Implement another loop that will increase the goal by doubling it at every iteration and report the conclusion. Keep all other variables fixed. The stake should be $5.

b. Implement another loop that will increase the trials by factors of 10 it at every iteration and report the conclusion. Keep all other variables fixed. The stake should be $5.

Challenge (Optional):

Add what is needed to be able to systematically increase both the goals and the trials. Report your result in full a sentence.

public class Gambler
{
    public static void main(String[] args)
   {
     int stake = Integer.parseInt(args[0]);
     int goal = Integer.parseInt(args[1]);
     int trials = Integer.parseInt(args[2]);

    int wins = 0;
    for (int i = 0; i < trials; i++)
     {
       int t = stake;
       while (t > 0 && t < goal)
        {
            if (Math.random() < 0.5) t++;
            else t--;
        }
        if (t == goal) wins++;
     }
   StdOut.println(wins + " wins of " + trials);  
   }
}

Conditionals: Gambler

The term gambler’s ruin is a statistical concept, most commonly expressed as the fact that a gambler playing a negative expected value game will eventually go broke, regardless of their betting system.

The original meaning of the term is that a persistent gambler who raises his bet to a fixed fraction of bankroll when he wins but does not reduce it when he loses, will eventually and inevitably go broke, even if he has a positive expected value on each bet.

Web-based app

 

Conditionals: The Crash of the AT&T Network in 1990



The Root Problem

The cause of the problem had come months before. In early December, technicians had upgraded the software to speed processing of certain types of messages. Although the upgraded code had been rigorously tested, a one-line bug was inadvertantly added to the recovery software of each of the 114 switches in the network. The defect was a C program that featured a break statement located within an if clause, that was nested within a switch clause.
In pseudocode, the program read as follows:

1  while (ring receive buffer not empty 
          and side buffer not empty) DO

2    Initialize pointer to first message in side buffer
     or ring receive buffer

3    get copy of buffer

4    switch (message)

5       case (incoming_message):

6             if (sending switch is out of service) DO

7                 if (ring write buffer is empty) DO

8                     send "in service" to status map

9                 else

10                    break

                  END IF

11           process incoming message, set up pointers to
             optional parameters

12           break
       END SWITCH


13   do optional parameter work

Input/Output: StdIn and StdOut for Filtering Data – stat

Assignment:
Extend program Stats.java shown below to create a filter that prints all the values that are further than 1.5 standard deviations from the mean. FilterStats_YI.java

Stats.java takes an integer N from the command line, reads N double values from standard input, and prints their mean (average value) and sample standard deviation (square root of the sum of the squares of their differences from the average, divided by N – 1).

[spoiler title=’Stats.java’]

Below is the syntax highlighted version of Stats.java from §1.5 Input and Output.


/******************************************************************************
 *  Compilation:  javac Stats.java
 *  Execution:    java Stats n
 *  Dependencies: StdIn.java StdOut.java
 *  
 *  Reads in a command-line integer n, a sequence of n real numbers from
 *  standard input, and prints the mean and sample standard deviation.
 *
 *  % java Stats 6
 *  10.0 5.0 6.0
 *  3.0 7.0 32.0
 *  
 *  Mean                      = 10.5
 *  Sample standard deviation = 10.784247771634329
 *
 *  Note  signifies the end of file on Unix.
 *  On windows use .
 *
 ******************************************************************************/

public class Stats { 
    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        double[] a = new double[n];

        // read data and compute statistics
        for (int i = 0; i < n; i++) {
            a[i] = StdIn.readDouble();
        }

        // compute mean
        double sum = 0.0;
        for (int i = 0; i < n; i++) {
            sum += a[i];
        }
        double mean = sum / n;

        // compute standard deviation
        double sum2 = 0.0;
        for (int i = 0; i < n; i++) {
            sum2 += (a[i] - mean) * (a[i] - mean);
        }
        double stddev = Math.sqrt(sum2 / (n - 1));

        // print results
        StdOut.println("Mean                      = " + mean);
        StdOut.println("Sample standard deviation = " + stddev);
    }
}

Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. Last updated: Fri Oct 20 14:12:12 EDT 2017. [/spoiler]

Khan Academy and Breakthrough Prize

“From now until October 7, Khan Academy and Breakthrough Prize are seeking video submissions that explain a challenging and important concept or theory in mathematics, life sciences, or physics. If you’re between 13 and 18, and you have a passion for explaining ideas and concepts creatively, you can enter the Breakthrough Junior Challenge!
Learn more about the Breakthrough Junior Challenge
Not only can you dig into a topic that you’re passionate about, but there are also great prizes to be won, including a $250,000 scholarship for you, a $50,000 award for your teacher, and a state-of-the-art $100,000 science lab for your school. The winner will also be invited California, where the prize will be awarded in front of the superstars of science, Silicon Valley, and Hollywood.

If you enter, you’ll view and assess other participants’ videos in a peer-to-peer review process. Submissions will then be assessed by leaders in science, technology, and education selected by Khan Academy and by Breakthrough Prize laureates. The judges will select a winner based on how engaging, illuminating, and creative their video is, and how challenging the concept is to understand.

The deadline for submissions is October 7, so register today at www.breakthroughjuniorchallenge.org. We hope you’ll be inspired to get involved – and share your passion for understanding the world!

Onward,

Erin and the Khan Academy content team”

Input/Output: StdDraw Exercises

MyTriangles_YI.java
Use StdDraw to implement MyTriangles_YI.java to create a drawing of 3 different triangles: acute, obtuse, and right. Look at this example.

MyFunctionGraph_YI.java
Run and understand how FunctionGraph.java works and modify it to create the graph of this function
y = sin(4x) + cos(20x)

Write a short paragraph about how the graph changes as the input argument changes.

<pre>

/******************************************************************************
 *  Compilation:  javac FunctionGraph.java 
 *  Execution:    java FunctionGraph n
 *  Dependencies: StdDraw.java
 *
 *  Plots the function y = sin(4x) + sin(20x) between x = 0 and x = pi
 *  by drawing n line segments.
 *
 ******************************************************************************/

public class FunctionGraph {
    public static void main(String[] args) {

        // number of line segments to plot
        int n = Integer.parseInt(args[0]);

        // the function y = sin(4x) + sin(20x), sampled at n+1 points
        // between x = 0 and x = pi
        double[] x = new double[n+1];
        double[] y = new double[n+1];
        for (int i = 0; i <= n; i++) {
            x[i] = Math.PI * i / n;
            y[i] = Math.sin(4*x[i]) + Math.sin(20*x[i]);
        }

        // rescale the coordinate system
        StdDraw.setXscale(0, Math.PI);
        StdDraw.setYscale(-2.0, +2.0);

        // plot the approximation to the function
        for (int i = 0; i < n; i++) {
            StdDraw.line(x[i], y[i], x[i+1], y[i+1]);
        }
    }
}
</pre>

Mystery Graph
Download the text file below and find out what the points draw.
Is the file missing anything?
Take a screenshot for submission.
Hint: use the PlotFinder.java