Category Archives: Homework

Input/Output: Graph Paper

Screen Shot 2015-02-23 at 12.19.21 AM

Classwork:
Write a program, MyGraphPaper_YI.java similar to CheckerBoard.java from below but to draw 2 different kinds of graph paper. Think of what graph paper you would use in a math class.

Study program CheckerBoard.java that takes a command-line argument N and plots an N-by-N checkerboard with red and black squares. It colors the lower left square red.

[spoiler title=’Checkerboard.java’]
Below is the syntax highlighted version of Checkerboard.java from §1.5 Input and Output.

/******************************************************************************
 *  Compilation:  javac Checkerboard.java 
 *  Execution:    java Checkerboard n
 *  Dependencies: StdDraw.java
 *
 *  Plots an n-by-n checkerboard.
 *
 ******************************************************************************/

public class Checkerboard { 

    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        StdDraw.setXscale(0, n);
        StdDraw.setYscale(0, n);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if ((i + j) % 2 != 0) StdDraw.setPenColor(StdDraw.BLACK);
                else                  StdDraw.setPenColor(StdDraw.RED);
                StdDraw.filledSquare(i + 0.5, j + 0.5, 0.5);
            }
        }
    }

}


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

[/spoiler]


RandomBlock_YI.java Animation
Use the tools from the BouncingBall program to implement RandomBlock_YI.java. This program re-uses the program from the graph paper assignment and randomly select squares on the grid that will become a solid color or “alive” and then randomly it will become back to white or “dead” again.

Input/Output: Graphics: CircleGradient.java and Gray

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

Classwork:

Remember to work on the current assignments before you work on this assignment.

Write a program, YI_CircleGradient.java to draw the following:
gradientcircle

Extra credit:
Write an animation program, YI_GrayGradient3D.java that shows the image below but the whitish to blackish region follows the mouse as the mouse moves over the ball.
graygradient3D

Input/Output: Animation: DeluxeBouncingBall.java

Screen Shot 2015-02-23 at 12.19.21 AM

Standard Drawing: Animation and images
Images. PU standard draw library supports drawing pictures as well as geometric shapes.

  • Images. Our standard draw library supports drawing pictures as well as geometric shapes. The command StdDraw.picture(x, y, filename) plots the image in the given filename (either JPEG, GIF, or PNG format) on the canvas, centered on (x, y).
  • Resources:
    https://introcs.cs.princeton.edu/java/15inout/TennisBall.png 
    https://introcs.cs.princeton.edu/java/15inout/pipebang.wav
  • User interaction. Our standard draw library also includes methods so that the user can interact with the window using the mouse.
    double mouseX()          return x-coordinate of mouse
    double mouseY()          return y-coordinate of mouse
    boolean mousePressed()   is the mouse currently being pressed?
    
      • A first example. MouseFollower.java is the HelloWorld of mouse interaction. It draws a blue ball, centered on the location of the mouse. When the user holds down the mouse button, the ball changes color from blue to cyan. A simple attractor. OneSimpleAttractor.java simulates the motion of a blue ball that is attracted to the mouse. It also accounts for a drag force.
      • Many simple attractors. SimpleAttractors.java simulates the motion of 20 blue balls that are attracted to the mouse. It also accounts for a drag force. When the user clicks, the balls disperse randomly.
      • Springs. Springs.java implements a spring system.

    Standard audio.

    StdAudio is a library that you can use to play and manipulate sound files. It allows you to play, manipulate and synthesize sound.

    We introduce some some basic concepts behind one of the oldest and most important areas of computer science and scientific computing: digital signal processing.

    • Concert A. Concert A is a sine wave, scaled to oscillate at a frequency of 440 times per second. The function sin(t) repeats itself once every 2π units on the x-axis, so if we measure t in seconds and plot the function sin(2πt × 440) we get a curve that oscillates 440 times per second. The amplitude (y-value) corresponds to the volume. We assume it is scaled to be between −1 and +1.
    • Other notes. A simple mathematical formula characterizes the other notes on the chromatic scale. They are divided equally on a logarithmic (base 2) scale: there are twelve notes on the chromatic scale, and we get the ith note above a given note by multiplying its frequency by the (i/12)th power of 2.

    • When you double or halve the frequency, you move up or down an octave on the scale. For example 880 hertz is one octave above concert A and 110 hertz is two octaves below concert A.
    • Sampling. For digital sound, we represent a curve by sampling it at regular intervals, in precisely the same manner as when we plot function graphs. We sample sufficiently often that we have an accurate representation of the curve—a widely used sampling rate is 44,100 samples per second. It is that simple: we represent sound as an array of numbers (real numbers that are between −1 and +1).
    •  

    For example, the following code fragment plays concert A for 10 seconds.

    int SAMPLING_RATE = 44100;
    double hz = 440.0;
    double duration = 10.0;
    int n = (int) (SAMPLING_RATE * duration);
    double[] a = new double[n+1];
    for (int i = 0; i <= n; i++) {
       a[i] = Math.sin(2 * Math.PI * i * hz / SAMPLING_RATE); 
    }
    StdAudio.play(a);
    • Play that tune. PlayThatTune.java is an example that shows how easily we can create music with StdAudio. It takes notes from standard input, indexed on the chromatic scale from concert A, and plays them on standard audio.

Input/Output: Animation: First One: Bouncing Ball

Your first animation using java!!!
duke

Screen Shot 2015-02-23 at 12.19.21 AM

Standard Drawing: Animation and images Images.

/******************************************************************************
 *  Compilation:  javac BouncingBall.java
 *  Execution:    java BouncingBall
 *  Dependencies: StdDraw.java
 *
 *  Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1).
 *
 *  % java BouncingBall
 *
 ******************************************************************************/

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

        // set the scale of the coordinate system
        StdDraw.setXscale(-1.0, 1.0);
        StdDraw.setYscale(-1.0, 1.0);
        StdDraw.enableDoubleBuffering();

        // initial values
        double rx = 0.480, ry = 0.860;     // position
        double vx = 0.015, vy = 0.023;     // velocity
        double radius = 0.05;              // radius

        // main animation loop
        while (true)  { 

            // bounce off wall according to law of elastic collision
            if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx;
            if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy;

            // update position
            rx = rx + vx; 
            ry = ry + vy; 

            // clear the background
            StdDraw.clear(StdDraw.GRAY);

            // draw ball on the screen
            StdDraw.setPenColor(StdDraw.BLACK); 
            StdDraw.filledCircle(rx, ry, radius); 

            // copy offscreen buffer to onscreen
            StdDraw.show();

            // pause for 20 ms
            StdDraw.pause(20);

        } 
    } 
} 


Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. 
Last updated: Tue Aug 30 09:58:33 EDT 2016.

Classwork:
Add this program to your current project.
Make the following changes, submit a screenshot for each change and the final program:

  1. Comment out the “clear” function and describe what you see. Remove the comments to continue working.
  2. Make the ball color change when it bounces. Choose a random color at every bounce.
  3. Change the background color from the original.
  4. Change the shape of the ball.

Reminder:

Array: as Frequency Counter

Classwork:
Write a program, BarGraph2_YI.java to create a bar graph with asterisks as in the previous bar graph. However, the array’s values are the raw data. Use this array and values, dataSet = { 67, 89, 55, 100, 95, 93, 57, 19, 88, 87, 86, 91,90}.


Output:
00-09:
10-19: *
20-29:
30-39:
40-49:
50-59: **
60-69: *
70-79: 
80-89: ****
90-99: ****
  100: *

Do not use if statements to check if the value fall within a range.
HINT: What is the result of dividing each grade by 10?
WARNING: DO NOT USE if STATEMENTS!!! or WHILE LOOPS TO FIND THE RANGE OF THE GRADES!!!

Claswork/Homework:

Consider the following:
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.” Randomly assign 20 responses to an integer array and determine the frequency of each rating.

cafeteriafood

Using what you learned about the elements of an array as counters, write a program, FoodSurvey_YI.java to display the rating and their frequency in two well formatted columns.

Output example:

Rating  Frequency
  1:       10
  2:        5
  3:        2
  4:        2
  5:        1

Arrays: 2D Arrays Intro

2D Arrays

Screen Shot 2014-11-21 at 9.58.20 AM

Screen Shot 2014-11-21 at 10.03.51 AM

Additional programming style guidelines:

/* 
 * 1. Make sure your program has indentation when is needed.
 * 2. Please include a comment line about local variables and group them all 
 *    together at the top of the program as long as it is not an OOD program.
 * 3. Never create a new local variable inside a loop!
 * 4. Have a blank line between different parts of the program
 */

final int COUNTRIES = 7;
final int MEDALS = 3;
int[][] counts = new int[COUNTRIES][MEDALS];

or but not both:

int[][] counts = {
 { 1, 0, 1 }, 
 { 1, 1, 0 }, 
 { 0, 0, 1 }, 
 { 1, 0, 0 }, 
 { 0, 1, 1 }, 
 { 0, 1, 1 }, 
 { 1, 1, 0 }
 };
for (int i = 0; i < COUNTRIES; i++)
{
  // Process the ith row
  for (int j = 0; j < MEDALS; j++) 
  {
      // Process the jth column in the ith row
      System.out.printf("%8d", counts[i][j]); 
  }
  System.out.println(); // Start a new line at the end of the row 
 }

Screen Shot 2014-11-21 at 10.09.23 AM

for (int i = 0; i < counts.length; i++) 
{
  for (int j = 0; j < counts[0].length; j++) 
  {
     System.out.printf("%8d", counts[i][j]); 
  }
  System.out.println(); 
}

Accessing the neighboring elements of a 2D array
Screen Shot 2014-11-21 at 10.11.40 AM

Screen Shot 2014-11-21 at 10.12.44 AM

Adding by rows:

int total = 0;
for (int i = 0; i < COUNTRIES; i++)
{
  total = 0;
  for (int j = 0; j < MEDALS; j++) 
  {
    total = total + counts[i][j];
  }
}

Screen Shot 2014-11-21 at 10.13.44 AM

Adding by columns:

int total = 0;
for (int j = 0; j < MEDALS; j++)
{
  total = 0;
  for (int i = 0; i < COUNTRIES; i++) 
  {
    total = total + counts[i][j]; 
  }
}

Classwork:
Write a program, MedalsTable_YI.java to produce the following output:

Screen Shot 2014-11-21 at 11.30.17 AM

Assignment:
Consider as an example an 8 × 8 array for a board game:
int[][] board = new int[8][8];

BoardGame_YI.java: Using two nested loops, initialize the board using "for" loops so that zeroes and ones alternate, as on a checkerboard. Prompt the user for the size of the "square" 2D array and display the board on the screen.

0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
...
1 0 1 0 1 0 1 0

Hint: Check whether i + j is even.

Arrays: Making Magic Squares

Screen Shot 2014-12-07 at 12.13.44 PM

2D Arrays

Classwork/Homework:

  1. Implement the following algorithm to construct magic n × n squares; it works only if n is odd.Set row = n – 1, column = n / 2.
    For k = 1 … n * n
    Place k at [row][column].
    Increment row and column.
    If the row or column is n, replace it with 0.
    If the element at [row][column] has already been filled
    { Set row and column to their previous values.
    Decrement row.}

    Here is the 5 × 5 square that you get if you follow this method:

    Screen Shot 2014-11-23 at 9.53.37 PM

    Write a program, MagicNSquare_YI.java whose input is the number n and whose output is the magic square of order n if n is odd. Include the code to check the new array is in fact a Magic Square. Display the sum of the columns, rows and diagonals.

  2. (Financial tsunami) Banks lend money to each other. In tough economic times, if a bank goes bankrupt, it may not be able to pay back the loan. A bank’s total assets are its current balance plus its loans to other banks. The diagram in the figure below shows five banks. The banks’ current balances are 25, 125, 175, 75, and 181 million dollars, respectively. The arrow from node 1 to node 2 indicates that bank 1 lends 40 million dollars to bank 2.

    If a bank’s total assets are under a certain limit, the bank is unsafe. The money it borrowed cannot be returned to the lender, and the lender cannot count the loan in its total assets. Consequently, the lender may also be unsafe, if its total assets are under the limit. Write a program, BankFinancing_YI.java to find all the unsafe banks. Your program reads the input as follows. It first reads two integers n and limit, where n indicates the number of banks and limit is the minimum total assets for keeping a bank safe. It then reads n lines that describe the information for n banks with IDs from 0 to n-1.
    The first number in the line is the bank’s balance, the second number indicates the number of banks that borrowed money from the bank, and the rest are pairs of two numbers. Each pair describes a borrower. The first number in the pair is the borrower’s ID and the second is the amount borrowed. For example, the input for the five banks in the figure is as follows (note that the limit is 201):

    5 201
    25 2 1 100.5 4 320.5
    125 2 2 40 3 85
    175 2 0 125 3 75
    75 1 0 125
    181 1 2 125
    

    The total assets of bank 3 are (75 + 125), which is under 201, so bank 3 is unsafe. After bank 3 becomes unsafe, the total assets of bank 1 fall below (125 + 40). Thus, bank 1 is also unsafe. The output of the program should be

    Unsafe banks are 3 1
    
    

    (Hint: Use a two-dimensional array borrowers to represent loans. borrowers[i][j] indicates the loan that bank i loans to bank j. Once bank j becomes unsafe, borrowers[i][j] should be set to 0.)

If you are done with every assignment, here is the next topics

PU Input and Output Standard classes

Book site
Screen Shot 2015-02-23 at 12.19.21 AM

Lesson’s pdf
Screen Shot 2015-11-22 at 4.48.06 PM

Create a new project:
InputOutput
You can get the following files from edmodo.com. Add them to your workspace:

StdIn.java
StdOut.java
StdDraw.java
StdAudio.java