Monthly Archives: October 2020

Advanced Topic: Static Identifier

The Static Specifier

foxtrot.100.in.binary

NOTE: use the implementation already written from the previous assignment but pay attention to the changes.
(The YI_MyStaticInteger class) Design a class named MyInteger. The class contains:
■ A static int data field named intCount that stores the number of object of this class created in the driver.
■ An int data field named value that stores the int value represented by this object.
■ A constructor that creates a MyStaticInteger object for the specified int value and updates the intCount data field.
■ A get method that returns the int value.
■ A get method that returns the int intCount.
■ The methods isEven(), isOdd(), and isPrime() that return true if the value in this object is even, odd, or prime, respectively.
■ The static methods isSEven(), isSOdd(), and isSPrime() that return true if the value in this object is even, odd, or prime, respectively. Comment out the code that causes any problem to be able to continue successfully with the implementation.
■ Compare the last two methods behaviors and explain the differences.
■ Report any problems and messages as comments and explain what the problem is. If you can’t figure it out, watch yesterday’s video again.
■ The static method getintCount() should be part of the class and used in the driver to display the number of object of MyStaticInteger class.

Conditionals: Car Loan

Classwork/Homework:

    1. Write a java program CarLoan_YI.java to print a table giving the total amount paid and the remaining principal after each monthly payment.
      • Prompt the user for the amount, interest and number of years.
      • The prompt should include relevant messages so the user understands the input format.
      • One of your runs should be with the data given below.

      NOTE: your program properly handles an interest rate of 0% and avoids dividing by 0.

      Click on the image to understand the formula

      Example output:
      Amount borrowed = 1000.00
      Number of years = 2

      Interest rate = 3.00
      Monthly payments = 42.98
      Total interest = 31.55
      If the total interest is pre-paid here is a chart:

      Month     Amt Paid      Remaining
       1           42.98         957.02
       2           85.96         914.04
       3          128.94         871.06
       4          171.92         828.08
       5          214.91         785.09
       6          257.89         742.11
       7          300.87         699.13
       8          343.85         656.15
       9          386.83         613.17
      10          429.81         570.19
      11          472.79         527.21
      12          515.77         484.23
      13          558.76         441.24
      14          601.74         398.26
      15          644.72         355.28
      16          687.70         312.30
      17          730.68         269.32
      18          773.66         226.34
      19          816.64         183.36
      20          859.62         140.38
      21          902.61          97.39
      22          945.59          54.41
      23          988.57          11.43
      
      

      If the total interest if included in the monthly payments, here is a chart:

      Courtesy from Diane Li

      /**
      Input/Output:
      Enter the loan amount in dollars:
      1000
      Enter the loan term in years:
      2
      Enter the annual interest rate as a percentage:
      3
      Month   Amount Paid   Remaining
      
      1     42.98          988.56
      2     85.96     945.58
      3    128.94     902.60
      4    171.92     859.62
      5    214.90     816.64
      6    257.88     773.66
      7    300.86     730.68
      8    343.84     687.69
      9    386.83     644.71
      10   429.81     601.73
      11   472.79     558.75
      12   515.77     515.77
      13   558.75     472.79
      14   601.73     429.81
      15   644.71     386.83
      16   687.69     343.84
      17   730.68     300.86
      18   773.66     257.88
      19   816.64     214.90
      20   859.62     171.92
      21   902.60     128.94
      22   945.58      85.96
      23   988.56      42.98
      24      1031.54           0.00
      
      **/
      

      Even though this chart doesn’t reflect the finance charge, it is an effective way to show the amount paid and the remaining values. In some cases, the finance charge is paid up front.
      screen-shot-2016-10-04-at-2-34-18-pm

      Optional

      screen-shot-2016-10-04-at-2-44-34-pm

       

      Car Loans | How Does Car Loan Interest Work? | IFS How does car loan interest affect you? Most car loans use simple interest. Learn more about car loan interest – it could save you money.

       

      If you really want the challenge of using the amortization model here is a chart that can show the effect of how the interest charges decrease as the amount borrowed also decreases.

      screen-shot-2016-10-04-at-2-44-34-pm

Conditionals: CompoundIntTable_YI.java – Needs fixing

Screen Shot 2014-09-23 at 10.00.31 AM

NO MORE MAGIC NUMBERS

Things to keep in mind when submitting your work:
1. Copy and paste your program in the post.
2. Attach your file(s).
3. Make sure your program has a header and the input/output.
4. If your program doesn’t run, an explanation should be the first line in the post.

Screen Shot 2014-09-28 at 12.38.49 PM

Classwork:
YI_CompoundIntTable.java: Use a while loop to show how the investment increases as the accumulated total becomes at least $1,100 at an interest rate of 1.2% when $1,000 is deposited in a savings bank account.

The table should have the following columns:


year      accum interest/year          total accumulated up to this year  
 1        12.0                         1012.0
 2        24.14                        1024.14
 3        36.43                        1036.43
...

Number of years for the investment of $1000 to reach at least a value of $1,100 with an interest rate of 1.2% is  8

Homework:
CompIntCompareTable_YI.java: Create another table that compares how you use the formula P(1+r)^t, where t is the number of years and how your program calculates the equivalent values.
End up your assignment with a conclusion about the similarities and the differences between the two approaches.

Conditionals: Project Euler

https://projecteuler.net/

About Project Euler

Leonhard Euler (1707-1783)

What is Project Euler?

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.

 

Who are the problems aimed at?

The intended audience include students for whom the basic curriculum is not feeding their hunger to learn, adults whose background was not primarily mathematics but had an interest in things mathematical, and professionals who want to keep their problem solving and mathematics on the cutting edge.

 

Can anyone solve the problems?

The problems range in difficulty and for many the experience is inductive chain learning. That is, by solving one problem it will expose you to a new concept that allows you to undertake a previously inaccessible problem. So the determined participant will slowly but surely work his/her way through every problem.

 

What next?

In order to track your progress it is necessary to setup an account and have Cookies enabled. If you already have an account then Login, otherwise please Register – it’s completely free!

However, as the problems are challenging then you may wish to view the Problems before registering.

 

“Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics.”

 

Conditionals: Monty Hall

monty-hall

Assignment:
Game simulation.
In the game show Let’s Make a Deal, a contestant is presented with three doors. Behind one door is a valuable prize, behind the other two are gag gifts. After the contestant chooses a door, the host opens up one of the other two doors (never revealing the prize, of course).

The contestant is then given the opportunity to switch to the other unopened door. Should the contestant do so? Intuitively, it might seem that the contestant’s initial choice door and the other unopened door are equally likely to contain the prize, so there would be no incentive to switch. Write a program MonteHall_YI.java to test this intuition by simulation.

Your program should take an integer command-line argument n, play the game n times using each of the two strategies (switch or don’t switch) and print the chance of success for each strategy.

End the program with a message stating the conclusion: Is a bigger chance of winning if you switch to a different door?

Conditionals: Asterisks

Screen Shot 2014-10-02 at 10.05.29 AM

Asterisks Pattern
If you are finished with yesterday’s programming assignment, work on the following assignment.
Write a program, Asterisks_YI.java that prints the following pattern separately, one below the other each pattern separated front he next by one blank line. Use nested for loops ONLY to generate the patterns. All asterisks (*) should be printed by a single statement
which causes the asterisks to print side by side separated by a space.
Hint: The last two patterns require that each line begin with an appropriate number of blanks.

Extra Credit: Combine your code from the four separate problems into a single program that prints all four patterns side by side by making clever use of nested for loops. For all parts of this program – minimize the number of statements that print these characters.
asteriskspattern

/**
 * 4 patterns using asterisks
 * Basic program to start with
 * It draws a square of asterisks
 *
 * @mrs.e
 * @11/19/19
 */
public class Asterisks
{
    public static void main(String args[])
    {
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                System.out.print("* ");
            }
            
            System.out.println();                   
        }
    }
}

* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 


Conditionals: Random Walker(s) Project

Screen Shot 2014-10-02 at 10.05.29 AM

Programming Project 1:
a. A drunkard’s walk. A drunkard begins walking aimlessly, starting at a lamp post. At each time step, the drunkard forgets where he or she is, and takes one step at random, either north, east, south, or west, with probability 25%. How far will the drunkard be from the lamp post after N steps?
More details on edmodo.com
Project 1 # 4: A drunkard’s walk

b. Write a program RandomWalkers.java that takes two integer command-line arguments N and T. In each of T independent experiments, simulate a random walk of N steps and compute the squared distance. Output the mean squared distance (the average of the T squared distances).

As N increases, we expect the random walker to end up farther and farther away from the origin. But how much farther? Use RandomWalkers to formulate a hypothesis as to how the mean squared distance grows as a function of N. Use T = 100,000 trials to get a sufficiently accurate estimate.

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 **/