Category Archives: Assignment

Input/Output: Graphics and Arrays: A Bar graph

Screen Shot 2015-02-23 at 12.19.21 AM

Classwork:
Standard Drawing

 

Write a program, BarGraph_YI.java to draw a bar graph like the one in the picture above.

Create an array of 100 random positive integer numbers between 1 and 20 inclusive. 

Find the min and max for both scales, x and y so you can determine the Xscale and Yscale for your canvas. Store in two arrays the approximate values for each of the bars in the image. Those values represent the frequency (y axis) and the value for the x coordinate. Make the width of each bar equal to 1.

Example: Bar 1: starts at 2 and the height is 5. This means 5 counts of 2.

Bar 2: starts at 4 and the height is 1. This means 1 count of 4. … and so on.

The idea behind the assignment: Use the x and y values to draw rectangles.

Suggestions: Make the Xscale and Yscale a bit larger than the min and max so the bar graph has a margin.

Tracing the trick for this assignment

Challenge: instead of drawing the bars at 2 or 3 or 4, draw then starting at 1.5, 2.5, 3.5 so the middle of the bar for 2 is on 2.

Labels are extra credit.

Arrays: The Locker Puzzle

Screen Shot 2014-12-07 at 12.13.44 PM

A school has 100 lockers and 100 students. All lockers are closed on the first day of school. As the students enter, the first student, denoted S1, opens every locker. Then the second student, S2, begins with the second locker, denoted L2, and closes every other locker. Student S3 begins with the third locker and changes every third locker (closes it if it was open, and opens it if it was closed). Student S4 begins with locker L4 and changes every fourth locker. Student S5 starts with L5 and changes every fifth locker, and so on until student S100 changes L100.
After all the students have passed through the building and changed the lockers, which lockers are open?

Write a program, WhichLockers_YI.java to find your answer and display all open locker numbers separated by exactly one space.

Hint: Use an array of 100 Boolean elements, each of which indicates whether a locker is open (true) or closed (false). Initially, all lockers are closed.

Input/Output: Animations: Ballistic Motion I

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

Classwork:
Projectile motion with drag. Use the supplied program and make the necessary changes to show during the animation the following:
Ballistic Motion Sim

Projectile motion with drag. Write a program YI_BallisticMotion1.java that plots the trajectory of a ball that is shot with velocity v at an angle theta. Account for gravitational and drag forces. Assume that the drag force is proportional to the square of the velocity. Using Newton’s equations of motions and the Euler-Cromer method, update the position, velocity, and acceleration according to the following equations:

Use the given program to enhance it to show the image bellow:
1. The values should change as the ball travels through the air.
2. The values should move with the ball.
3. The blue text and dotted curve is not included in the GUI.

project motion math

[spoiler title=’BallisticMotion.java’]

/******************************************************************************
* Compilation: javac BallisticMotion.java
* Execution: java BallisticMotion v theta
* Dependencies: StdDraw.java
*
* Simluate the motion of a ball fired with velocity v at theta degrees
* with coefficient of drag C. Uses Euler-Cramer method to numerically
* solve differential equation.
*
* % java BallisticMotion 180.0 60.0
*
* % java BallisticMotion 20.0 45.0
* Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.
* Last updated: Mon Aug 3 12:15:11 EDT 2015.
******************************************************************************/

public class BallisticMotion {

public static void main(String[] args) {
double G = 9.8; // gravitational constant m/s^2
double C = 0.002; // drag force coefficient

double v = Double.parseDouble(args[0]); // velocity
double theta = Math.toRadians(Double.parseDouble(args[1])); // angle in radians

double x = 0.0, y = 0.0; // position
double vx = v * Math.cos(theta); // velocity in x direction
double vy = v * Math.sin(theta); // velocity in y direction

double ax = 0.0, ay = 0.0; // acceleration
double t = 0.0; // time
double dt = 0.01; // time quantum

double maxR = v*v / G; // maximum distance without drag force
StdDraw.setXscale(0, maxR);
StdDraw.setYscale(0, maxR); // set the same as for X-scale

// loop until ball hits ground
while (y >= 0.0) {
v = Math.sqrt(vx*vx + vy*vy);
ax = -C * v * vx;
ay = -G – C * v * vy;
vx += ax * dt;
vy += ay * dt;
x += vx * dt;
y += vy * dt;StdDraw.filledCircle(x, y, 0.25);
StdDraw.show();
StdDraw.pause(5);
StdDraw.clear();

}

StdDraw.show();
}

}

[/spoiler]

Homework:
Work on the ballistic motion assignment.

Input/Output: Animations: Array: Intro to Conways’ Game of Life

Conways’ Game of Life
Gospers_glider_gun

Answer the following questions in edmodo.com
1. What is the shape of the cells?
2. What are the two possible states of a cell?
3. How many neighboring cells each cell interact with?
4. Explain the relative location of these neighboring cells.
5. What are the rules at each step in time?
6. What does the initial pattern constitute?
7. What is it referred by a “tick”?
8. What are the criteria that must be met for the proper emulation to be successful?
9. What are the different types of pattern that occur in the Game of Life?
10. On a piece of graph paper draw the 3 following patterns and show the life of the cell at each of 5 ticks.
Beehive
Screen Shot 2014-12-15 at 11.12.40 PM

Beacon
Screen Shot 2014-12-15 at 11.13.08 PM

Glider
Screen Shot 2014-12-15 at 11.13.32 PM

Write the first draft of your algorithm using only pseudocode.
One of many Fun sites


Animation: RandomBlock_YI.java

Implement an animation, RandomBlock_YI.java. The CheckerBoard.java can easily be changed to randomly select a random number of squares on the grid and become a solid color (“alive”) and then randomly it will turn back to white (“dead”) again. ‌ Re-Use-Code: these are good resources for this assignment: ‌

BouncingBall.java

CheckerBoard.java

MyGraphPaper.java

If you have successfully completed the random block program, you should be able to get started with the game of life assignment.
Start small. Here is the glider:

OOD – Encapsulation

Clearly explain the difference and similarities between these two lines of code:

harrysChecking.balance -= 500; // assume balance is not private (no encapsulation)

harrysChecking.withdraw(500); // encapsulation is enforced

Which one would you pick if you were Harry? Support your answer.

OOD: Employee

employees

Implement a class Employee_YI. An employee has a name (a string) and a salary (a double). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Write a tester/driver program that tests your class.
 

NOTE: Do not forget to document your work. Include header, a comment line for each method and constructor and input/output.

OOD w Animations: The Dodge

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

Look at the following programs, add them to your project, play with them and understand them. You can use them to create your Dodge Game. However, you must use ArrayLists. 

MouseFollower.java
OneSimpleAttractor.java
SimpleAttractors
Springs.java

Classwork:
The Dodge Game. Implement the game dodge using StdDraw: move a blue disc within the unit square to touch a randomly placed green disc, while avoiding the moving red discs. After each touch, add a new moving red disc.

 

 

/******************************************************************************
 *  Compilation:  javac MouseFollower.java
 *  Execution:    java MouseFollower
 *  Dependencies: StdDraw.java
 *
 *  Draw a blue filled circle wherever the mouse is, in cyan if the
 *  mouse is pressed.
 *
 *
 *  % java MouseFollower
 *
 *  Credits:  Jeff Traer-Bernstein
 *
 ******************************************************************************/


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

        StdDraw.enableDoubleBuffering();

        while (true) {

            // mouse click
            if (StdDraw.isMousePressed()) StdDraw.setPenColor(StdDraw.CYAN);
            else                          StdDraw.setPenColor(StdDraw.BLUE);

            // mouse location
            StdDraw.clear();
            double x = StdDraw.mouseX();
            double y = StdDraw.mouseY();
            StdDraw.filledCircle(x, y, 0.05);
            StdDraw.show();
            StdDraw.pause(10);
        }
    }
}


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

/******************************************************************************
 *  Compilation:  javac OneSimpleAttractor.java
 *  Execution:    java OneSimpleAttractor
 *  Dependencies: StdDraw.java
 *
 *  A particle is attracted to the current location of the mouse.
 *  Incorporates drag.
 *
 *  
 *  % java OneSimpleAttractor
 *
 *
 *  Credits:  Jeff Traer-Bernstein
 *
 ******************************************************************************/



public class OneSimpleAttractor {
    public static void main(String[] args) {
        double rx = 0.0, ry = 0.0;   // position
        double vx = 0.0, vy = 0.0;   // velocity
        double mass = 1.0;           // mass
        double dt   = 0.5;           // time quantum
        double drag = 0.1;           // mess around with this a bit
        double attractionStrength = 0.01;
        
        // do the animation
        StdDraw.enableDoubleBuffering();
        while (true) {

            // compute the attractive force to the mouse, accounting for drag
            double dx = StdDraw.mouseX() - rx;
            double dy = StdDraw.mouseY() - ry;
            double fx = (dx * attractionStrength) - (drag * vx);
            double fy = (dy * attractionStrength) - (drag * vy);
    
            // Euler step: update velocity, then position
            vx += fx * dt / mass;
            vy += fy * dt / mass;
            rx += vx * dt;
            ry += vy * dt;
            
            // draw particle
            StdDraw.clear();
            StdDraw.setPenColor(StdDraw.BLUE);
            StdDraw.filledCircle(rx, ry, 0.02);
            StdDraw.show();
            StdDraw.pause(10);
        }
    }
}


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

/******************************************************************************
 *  Compilation:  javac SimpleAttractors.java
 *  Execution:    java SimpleAttractors n
 *  Dependencies: StdDraw.java
 *
 *  n particles are attracted to the mouse; randomly rearrange when
 *  user clicks.
 *
 *  % java SimpleAttractors 20
 *
 *  Credits:  Jeff Traer-Bernstein
 * 
 ******************************************************************************/
public class SimpleAttractors {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        double[] rx = new double[n];
        double[] ry = new double[n];
        double[] vx = new double[n];
        double[] vy = new double[n];
        double dt = 0.5;
        double mass = 1.0;
        double drag = 0.05;     // try changing this to 0.1 or 0.01 or even 0...
        double attractionStrength = 0.01;
        
        // initialize the drawing area
        StdDraw.setPenColor(StdDraw.BLUE);
        StdDraw.enableDoubleBuffering();
        StdDraw.setScale(-1, +1);
        // do the animation
        while (true) {
            // if the mouse is pressed add some random velocity to all the particles
            if (StdDraw.isMousePressed()) {
                for (int i = 0; i < n; i++) {
                    vx[i] = 0.2 * Math.random() - 0.1;
                    vy[i] = 0.2 * Math.random() - 0.1;
                }
            }
            
            // clear all the forces
            double[] fx = new double[n];
            double[] fy = new double[n];
            
            // add attraction forces for attraction to the mouse
            for (int i = 0; i < n; i++) {
                double dx = StdDraw.mouseX() - rx[i];
                double dy = StdDraw.mouseY() - ry[i];
                fx[i] += attractionStrength * dx;
                fy[i] += attractionStrength * dy;
            }
            
            // add drag forces to all particles
            // drag is proportional to velocity in the opposite direction
            for (int i = 0; i < n; i++) {
                fx[i] += -drag * vx[i];
                fy[i] += -drag * vy[i];
            }
            
            // update positions
            // euler step
            for (int i = 0; i < n; i++) {
                vx[i] += fx[i] * dt / mass;
                vy[i] += fy[i] * dt / mass;
                rx[i] += vx[i] * dt;
                ry[i] += vy[i] * dt;
            }
            
            
            StdDraw.clear();
            
            // draw a filled circle for each particle
            for (int i = 0; i < n; i++) {
                StdDraw.filledCircle(rx[i], ry[i], 0.01);
            }
            
            StdDraw.show();
            StdDraw.pause(10);
        }
    }
}
/******************************************************************************
 *  Compilation:  javac Springs.java
 *  Execution:    java Springs N
 *  Dependencies: StdDraw.java
 *
 *  Simulates a system of springs.
 *
 *  % java Springs 15
 *
 *  Credits:  Jeff Traer-Bernstein
 *
 ******************************************************************************/
public class Springs {
    public static void main(String[] args) {
        // mess around with this, try 7, 8, 9, 10, 11, 12, 15
        // probably have to turn down the spring force to keep it stable after that...
        int n = Integer.parseInt(args[0]);
        double[] rx = new double[n];
        double[] ry = new double[n];
        double[] vy = new double[n];
        double[] vx = new double[n];
        double particleMass = 1.0;
        double drag = 0.1;
        double springStrength = 0.1;
        double springLength = 30;
        double gravity = 1.0;
        double timeStep = 0.5;
        
        // set up the drawing area
        StdDraw.setXscale(0, 100);
        StdDraw.setYscale(0, 100);
        StdDraw.setPenColor(StdDraw.BLUE);
        StdDraw.setPenRadius(0.0025);
        StdDraw.enableDoubleBuffering();
        
        // initialize the particle positions randomly
        for (int i = 0; i < n; i++) {
            rx[i] = 100 * Math.random();
            ry[i] = 100 * Math.random();
        }
        
        
        // do the animation
        while (true) {
            // clear all the forces
            double[] fx = new double[n];
            double[] fy = new double[n];
            
            // spring forces act between every pairing of particles
            // spring force is proportional to the difference between the rest length of the spring
            // and the distance between the 2 particles it's acting on
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == j) continue;
                    // calculate distance between particles i and j
                    double dx = rx[j] - rx[i];
                    double dy = ry[j] - ry[i];
                    double length = Math.sqrt(dx*dx + dy*dy);
                    
                    // figure out the force
                    double force = springStrength * (length - springLength);
                    double springForceX = force * dx / length;
                    double springForceY = force * dy / length;
                    
                    // update the force
                    fx[i] += springForceX;
                    fy[i] += springForceY;
                }
            }
            
            // add drag force
            // drag is proportional to velocity but in the opposite direction
            for (int i = 0; i < n; i++) {
                fx[i] += -drag * vx[i];
                fy[i] += -drag * vy[i];
            }
            
            // add gravity forces
            // just add some force pointing down to all of them
            for (int i = 0; i < n; i++) {
                fy[i] += -gravity;
            }
            
            // fix particle 1 at the mouse position
            rx[0] = StdDraw.mouseX();
            ry[0] = StdDraw.mouseY();
            vx[0] = 0.0;
            vy[0] = 0.0;
            fx[0] = 0.0;
            fy[0] = 0.0;
            
            // update positions using approximation
            for (int i = 0; i < n; i++) {
                vx[i] += fx[i] * timeStep/particleMass;
                vy[i] += fy[i] * timeStep/particleMass;
                rx[i] += vx[i] * timeStep;
                ry[i] += vy[i] * timeStep;
            }
            
            
            // clear
            StdDraw.clear();
            
            // draw everything
            for (int i = 0; i < n; i++) {
                // draw a circle for each node
                StdDraw.filledCircle(rx[i], ry[i], 1.0);
                
                // draw the connections between every 2 nodes
                for (int j = 0; j < i; j++) {
                    StdDraw.line(rx[i], ry[i], rx[j], ry[j]);
                }
            }
            
            // show and wait
            StdDraw.show();
            StdDraw.pause(10);
        }
    }
}
Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. 
Last updated: Fri Oct 20 14:12:12 EDT 2017.

If you are missing isMousePressed in any of your programs, you should copy the StdDraw below to your original. StdDraw Code

OOD – Cell Mitosis w/StdDraw

You have already written an ADT, Cell_YI with the instance fields, the attributes which identify all the different components in a cell. In this assignment, you will add a new feature, the draw methods using StdDraw.

Before you get started, think about how you are going to break up the images to show the different phases of the mitosis.

Here are some of the resources you can use for the Cell Mitosis and other animations/simulations: 3 Options:
-Take a cell image and using an image editor make the components of the cell separate images.


-Using multiple images and compile them into an array of “frames”

/*************************************************************************
 *  Compilation:  javac Duke.java
 *  Execution:    java Duke
 *  Dependencies: StdDraw.java StdIn.java
 *
 *  Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.
 *  Last updated: Wed Feb 9 09:02:07 EST 2011.
 *
 *
 *  Draw the sequence of images T1.gif to T17.gif. This creates
 *  the illusion of motion, where the Java mascot Duke cart-wheels
 *  across the screen.
 *
 *  Reference: http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/index.html#TumbleItem
 *
 *************************************************************************/

public class Duke {

    public static void main(String[] args) {
        int images = 17;                        // number of images
        int WIDTH = 130, HEIGHT = 80;           // images are 130-by-80
        StdDraw.setCanvasSize(WIDTH, HEIGHT);
        StdDraw.setXscale(0, WIDTH);
        StdDraw.setYscale(0, HEIGHT);

        // main animation loop
        for (int t = 0; true; t++) {
            int i = 1 + (t % images);
            String filename = "T" + i + ".gif";  // name of the ith image
            StdDraw.picture(WIDTH/2.0, HEIGHT/2.0, filename);
            StdDraw.show();
            StdDraw.pause(100);
        }
    }

}


-Make your own images by drawing them with an app like the one attached. This will allow you to manipulate the individual components of the cell easier and it will have a fluent transformation. It will look pixelated but that is not a bad thing at all.
https://www.piskelapp.com/


If you need to scale pictures, you can use this method from StdDraw:

/**
 Draws the specified image centered at (x, y),
 rescaled to the specified bounding box.
 The supported image formats are JPEG, PNG, and GIF.

 @param x the center x-coordinate of the image
 @param y the center y-coordinate of the image
 @param filename the name of the image/picture, e.g., "ball.gif"
 @param scaledWidth the width of the scaled image (in screen coordinates)
 @param scaledHeight the height of the scaled image (in screen coordinates)
 @throws IllegalArgumentException if either {@code scaledWidth}
 or {@code scaledHeight} is negative
 @throws IllegalArgumentException if the image filename is invalid
*/
public static void picture(double x, double y, String filename, 
double scaledWidth, double scaledHeight)

/******************************************************************************
 *  Compilation:  javac BouncingBallDeluxe.java
 *  Execution:    java BouncingBallDeluxe
 *  Dependencies: StdDraw.java StdAudio.java
 *                https://introcs.cs.princeton.edu/java/15inout/TennisBall.png
 *                https://introcs.cs.princeton.edu/java/15inout/pipebang.wav
 *
 *  Implementation of a bouncing tennis ball in the box from (-1, -1) to (1, 1),
 *  with sound effects.
 *
 *  % java BouncingBallDeluxe
 *
 ******************************************************************************/

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

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

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

        // main animation loop
        while (true) { 

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

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

            // set the background to light gray
            StdDraw.clear(StdDraw.LIGHT_GRAY);

            // draw ball on the screen
            StdDraw.picture(rx, ry, "TennisBall.png");

            // display and pause for 20ms
            StdDraw.show();
            StdDraw.pause(20); 
        } 
    } 
} 



/**
 * Turning a functional program to an ADT application.
 * 
 * @GE
 * @java 1.8 date: 1/18/19
 */
public class Ball
{
    private double rx = 0.480, ry = 0.860;     // position
    private double vx = 0.015, vy = 0.023;     // velocity
    private double radius = 0.05;   

    public double rx()
    {
        return rx;
    }

    public double ry()
    {
        return ry;
    }

    public void setRx(double rx)
    {
        this.rx = rx;
    }

    public void setRy(double ry)
    {
        this.ry = ry;
    }

    public double[] getVel()
    {
        double [] vel = { vx, vy};
        return vel;
    }

    public void setVx(double vx)
    {
        this.vx = vx;
    }

    public void setVy(double vy)
    {
        this.vy = vy;
    }

    public double radius()
    {
        return radius;
    }
}

/******************************************************************************
 *
 *  Implementation of a bouncing tennis ball in the box from (-1, -1) to (1, 1),
 *  with sound effects.
 *
 *  % java BouncingBallODD
 *
 ******************************************************************************/

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

        Ball bouncy = new Ball();
        

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

        // main animation loop
        while (true) { 

            // bounce off wall according to law of elastic collision
            if (Math.abs(bouncy.rx() + bouncy.getVel()[0]) + bouncy.radius() > 1.0) {
                bouncy.setVx(-bouncy.getVel()[0]);
                
            }
            if (Math.abs(bouncy.ry() + bouncy.getVel()[1]) + bouncy.radius() > 1.0) {
                bouncy.setVy(-bouncy.getVel()[1]);
                
            }

            // update position
            bouncy.setRx(bouncy.rx() + bouncy.getVel()[0]); 
            bouncy.setRy(bouncy.ry() + bouncy.getVel()[1]); 

            // set the background to light gray
            StdDraw.clear(StdDraw.LIGHT_GRAY);

            // draw ball on the screen
            StdDraw.picture(bouncy.rx(), bouncy.ry(), "TennisBall.png");

            // display and pause for 20ms
            StdDraw.show();
            StdDraw.pause(20); 
        } 
    } 
}