Author Archives: graceliana@gmail.com

Recursion in Graphics: Sierpiński triangle Checklist

Recursive Graphics Programming Assignment Checklist

Assignment Page

Frequently Asked Questions:  Transform2D

What preparation do I need before beginning this assignment? Read Sections 2.1–2.3 of the textbook.

The API expects the angles to be in degrees but Java’s trigonometric functions assume the arguments are in radians. How do I convert between the two? Recall GreatCircle.java from Assignment 0.

What is the purpose of the copy() function in Transform2D? As noted in the assignment, the transformation methods mutate a given polygon. This means that the parallel arrays representing the polygon are altered by the transformation methods. It is often useful to save a copy of the polygon before applying a transform. For example:

// Set the x- and y-scale
StdDraw.setScale(-5.0, 5.0);

// Original polygon
double[] x = { 0, 1, 1, 0 };
double[] y = { 0, 0, 2, 1 };

// Copy of original polygon
double[] cx = Transform2D.copy(x);
double[] cy = Transform2D.copy(y);

// Rotate, translate and draw the copy
Transform2D.rotate(cx, cy, -45.0);
Transform2D.translate(cx, cy, 1.0, 2.0);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.polygon(cx, cy);

// Draw the original polygon
StdDraw.setPenColor(StdDraw.RED);
StdDraw.polygon(x, y);
copy and polygon

Does a polygon have to be located at the origin in order to rotate it? No. You can rotate any polygon about the origin. For example:

// Original polygon
double[] x = { 1, 2, 2, 1 };
double[] y = { 1, 1, 3, 2 };
StdDraw.setPenColor(StdDraw.RED);
StdDraw.polygon(x, y);

// Rotate polygon
// 90 degrees counterclockwise
Transform2D.rotate(x, y, 90.0);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.polygon(x, y);
rotate any polygon

Does our code have to account for invalid arguments? No. You can assume:

  • the array passed to copy() is not null,
  • arrays passed to scale()translate() and rotate() are not null, are the same length, and do not contain the values NaN,infinity or negative infinity.
  • the values for the parameters alphathetadx and dy are not NaN, infinity or negative infinity.
Frequently Asked Questions:  Sierpinski

What is the formula for the height of an equilateral triangle of side length s? The height is (s \sqrt{3} / 2 ).

height of an equilateral triangle
What is the layout of the initial equilateral triangle? The top vertex lies at ((1/2, \sqrt{3} / 2)) You can use this diagram as a reference.

Sierpinski triangle geometry

How do I draw a filled equilateral triangle? Call the method StdDraw.filledPolygon() with appropriate arguments.

I get a StackOverflowError message even when n is a very small number like 3. What could be wrong? This means you are running out of space to store the function-call stack. Often, this error is caused by an infinite recursive loop. Have you correctly defined the base case and reduction step?

May I use different colors to draw the triangles? Yes, you may use any colors that you like to draw either the outline triangle or the filled triangles, provided it contrasts with the white background.

Frequently Asked Questions:  Art

The API checker says that I need to make my methods private. How do I do that? Use the access modifier private instead of public in the method signature. A public method can be called directly by a method in another class; a private method cannot. The only public method that you should have in Art is main().

How should I approach the artistic part of the assignment? This part is meant to be fun, but here are some guidelines in case you’re not so artistic. A very good approach is to first choose a self-referential pattern as a target output. Check out the graphics exercises in Section 2.3. Here are some of our favorite student submissions from a previous year. See also the Famous Fractals in Fractals Unleashed for some ideas. Here is a list of fractals, by Hausdorff dimension. Some pictures are harder to generate than others (and some require trigonometry); consult your preceptor for advice if you’re unsure.

What will cause me to lose points on the artistic part? We consider three things: the structure of the code; the structure of the recursive function-call tree; and the art itself.

For example, the Quadricross looks very different from the in-class examples, but the code to generate it looks extremely similar to HTree, so it is a bad choice. On the other hand, even though the Sierpinski curve eventually generates something that looks like the Sierpinski triangle, the code is very different (probably including an “angle” argument in the recursive method) and so it would earn full marks.

You must do at least two of these things to get full credit on Art.java:

  • call one or more Transform2D method
  • use different parameters than our examples: f(n, x, y, size)
  • use different StdDraw methods than in examples (e.g., ellipses, arcs, text)
  • number of recursive calls not constant per level (e.g., conditional recursion)
  • mutually recursive methods
  • multiple recursive methods
  • doesn’t always recur from level n to level n-1
  • draw between recursive calls, not just before or after all recursive calls
  • use recursive level for secondary purpose (e.g. level dictates color)

Contrast this with the examples HtreeSierpinski, and NestedCircles which have very similar structures to one another.

You will also lose points if your artwork can be created just as easily without recursion (such as Factorial.java). If the recursive function-call tree for your method is a straight line, it probably falls under this category.

May I use GIF, JPG, or PNG files in my artistic creation? Yes. If so, be sure to submit them along with your other files. Make it clear in your readme.txt what part of the design is yours and what part is borrowed from the image file.

How can I call the Transform2D methods inside Art.java? You must fully qualify each method name with the Transform2D library. For example:

Transform2D.rotate(x, y, 45);

My function for Art.java takes several parameters, but the assignment says that I can only read in one command-line argument n. What should I do? Choose a few of the best parameter values and do something like the following:

if      (n == 1) { x = 0.55; y = 0.75; }
else if (n == 2) { x = 0.55; y = 0.75; }
else if (n == 3) { x = 0.32; y = 0.71; }
else if ...

How can I create colors that aren’t predefined in standard drawing? It requires using objects that we’ll learn about in Chapter 3. In the meantime, you can use this color guide.

Possible Progress Steps:  Sierpinski

These are purely suggestions for how you might make progress. You do not have to follow these steps. Note that your final Sierpinski.java program should not be very long (no longer than Htree, not including comments and blank lines).

  • Review Htree.java from the textbook and lecture.
  • Write the (non-recursive) function height() that takes the length of the sides in an equilateral triangle as an argument and returns its height. The body of this method should be a one-liner.Test your height() function.
  • Write a (nonrecursive) function filledTriangle() that takes three real-valued arguments (xy, and length), and draws a filled equilateral triangle (pointed downward) with bottom vertex at (xy) of the specified side length.To debug and test your function, write main() so that it calls filledTriangle() a few times, with different arguments. You will be able to use this function without modification in Sierpinski.java.
  • Write a recursive function sierpinski() that takes four (4) arguments (nxy, and length) and plots a Sierpinski triangle of order n, whose largest triangle has bottom vertex (xy) and the specified side length.
    • Write a recursive function sierpinski() that takes one argument n, prints the value n, and then calls itself three times with the value n-1. The recursion should stop when n becomes 0. To test this function out, write main() so that it takes an integer command-line argument n and calls sierpinski(n). Ignoring whitespace, you should get the following output when you call sierpinski() with n ranging from 0 to 5. Make sure you understand how this function works, and why it prints the numbers in the order it does.
    • Modify sierpinski() so that in addition to printing n, it also prints the length of the triangle to be plotted. Your function should now take two arguments: n and length. The initial call from main() should be to sierpinski(n, 0.5) since the largest triangle has side length 0.5. Each successive level of recursion halves the length. Ignoring whitespace, your function should produce the following output.
    • Modify sierpinski() so that it takes four (4) arguments (nxy, and length) and plots a Sierpinski triangle of order n, whose largest triangle has bottom vertex (xy) and the specified side length. Start by drawing Sierpinski triangles with pencil and paper. Use the picture in the Q+A above to figure out the geometry of where the smaller Sierpinski triangles should go.
    • Remove all print statements before submitting.
  • Below are the target Sierpinski triangles for different values of n.
    java-introcs Sierpinski 1 java-introcs Sierpinski 2 java-introcs Sierpinski 3
    Sierpinski triangle of order 1 Sierpinski triangle of order 2 Sierpinski triangle of order 3
Reviewing Your Program
  • Transform2D.java: The main must call each of the methods defined by the Transform2D API.
  • Sierpinski.javaDo not call StdDraw.save()StdDraw.setCanvasSize()StdDraw.setXscale()StdDraw.setYscale(), or StdDraw.setScale(). These method calls interfere with grading. (However, changing the x– or y-scales in Transform2D.java and Art.java is permitted.)
  • Art.javaMust take exactly one integer command-line argument n (which will be between 1 and 7).
  • Be sure to include a comment just above each method definition explaining what the method does—this will be required in all future assignments as well. Leaving a comment for main() is not required since the header already does basically the same thing.
  • Continue to follow the style guidelines from the assignment FAQ.
Enrichment
  • Fractals in the wild. Here’s a Sierpinski triangle in polymer clay, a Sierpinski carpet cookie, a fractal pizza, and a Sierpinski hamantaschen.
  • Fractal dimension (optional diversion).   In grade school, you learn that the dimension of a line segment is 1, the dimension of a square is 2, and the dimension of a cube is 3. But you probably didn’t learn what is really meant by the term dimension. How can we express what it means mathematically or computationally? Formally, we can define the Hausdorff dimension or similarity dimension of a self-similar figure by partitioning the figure into a number of self-similar pieces of smaller size. We define the dimension to be the log (# self similar pieces) / log (scaling factor in each spatial direction). For example, we can decompose the unit square into 4 smaller squares, each of side length 1/2; or we can decompose it into 25 squares, each of side length 1/5. Here, the number of self-similar pieces is 4 (or 25) and the scaling factor is 2 (or 5). Thus, the dimension of a square is 2 since log (4) / log(2) = log (25) / log (5) = 2. We can decompose the unit cube into 8 cubes, each of side length 1/2; or we can decompose it into 125 cubes, each of side length 1/5. Therefore, the dimension of a cube is log(8) / log (2) = log(125) / log(5) = 3.We can also apply this definition directly to the (set of white points in) Sierpinski triangle. We can decompose the unit Sierpinski triangle into 3 Sierpinski triangles, each of side length 1/2. Thus, the dimension of a Sierpinski triangle is log (3) / log (2) ≈ 1.585. Its dimension is fractional—more than a line segment, but less than a square! With Euclidean geometry, the dimension is always an integer; with fractal geometry, it can be something in between. Fractals are similar to many physical objects; for example, the coastline of Britain resembles a fractal; its fractal dimension has been measured to be approximately 1.25.

Recursion in Graphics: Sierpiński triangle

https://www.cs.princeton.edu/courses/archive/spring17/cos126/assignments/sierpinski.html

 

This assignments consists of three parts. First, write a library of static methods that performs geometric transforms on polygons. Next, write a program that plots a Sierpinski triangle. Finally, develop a program that plots a recursive pattern of your own design.

Part 1.   In this part, you will write a library of static methods that performs various geometric transforms on polygons. Mathematically, a polygon is defined by its sequence of vertices (x0y0), (x1y1), (x2y2), …. In Java, we will represent a polygon by storing the x– and y-coordinates of the vertices in two parallel arrays x[] and y[].

StdDraw and polygon
<pre>// Represents the polygon with vertices (0, 0), (1, 0), (1, 2), (0, 1).
double x[] = { 0, 1, 1, 0 };
double y[] = { 0, 0, 2, 1 };
</pre>

Three useful geometric transforms are scaletranslate and rotate.

  • Scale the coordinates of each vertex (xiyi) by a factor α.

    \( \begin{align*} x_i’ \;&=\; \alpha \, x_i \\ y_i’ \;&=\; \alpha \, y_i \end{align*} \)

  • Translate each vertex (xiyi) by a given offset (dxdy).

    \( \begin{align*} x_i’ \;&=\; x_i \;+\; dx \\ y_i’ \;&=\; y_i \;+\; dy \end{align*} \)

  • Rotate each vertex (xiyi) by θ degrees counterclockwise, around the origin.

    \( \begin{align*} x_i’ \;&=\; x_i \cos \theta \;-\; y_i \sin \theta \\ y_i’ \;&=\; y_i \cos \theta \;+\; x_i \sin \theta \end{align*} \)

Write a two-dimensional transformation library Transform2D.java by implementing the following API:

public class Transform2D {

    // Returns a new array object that is an exact copy of the given array.
    // The given array is not be mutated.
    public static double[] copy(double[] array)

    // Scales the polygon by the factor alpha.
    public static void scale(double[] x, double[] y, double alpha)

    // Translates the polygon by (dx, dy).
    public static void translate(double[] x, double[] y, double dx, double dy)

    // Rotates the polygon theta degrees counterclockwise, about the origin.
    public static void rotate(double[] x, double[] y, double theta)

    // Tests each of the API methods by directly calling them.
    public static void main(String[] args)
}

Note that the transformation methods scale()translate() and rotate() mutate the polygons. Here are some example test cases:

// Scales polygon by the factor 2.
StdDraw.setScale(-5.0, +5.0);
double[] x = { 0, 1, 1, 0 };
double[] y = { 0, 0, 2, 1 };
double alpha = 2.0;
StdDraw.setPenColor(StdDraw.RED);
StdDraw.polygon(x, y);
scale(x, y, alpha);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.polygon(x, y);

 
Scale a polygon
 

Part 2.   The Sierpinski triangle is an example of a fractal pattern like the H-tree pattern from Section 2.3 of the textbook.

Sierpinski triangle of order 1 Sierpinski triangle of order 2 Sierpinski triangle of order 3 Sierpinski triangle of order 4 Sierpinski triangle of order 5 Sierpinski triangle of order 6
order 1 order 2 order 3 order 4 order 5 order 6

The Polish mathematician Wacław Sierpiński described the pattern in 1915, but it has appeared in Italian art since the 13th century. Though the Sierpinski triangle looks complex, it can be generated with a short recursive function. Your main task is to write a recursive function sierpinski() that plots a Sierpinski triangle of order n to standard drawing. Think recursively: sierpinski() should draw one filled equilateral triangle (pointed downwards) and then call itself recursively three times (with an appropriate stopping condition). It should draw 1 filled triangle for n = 1; 4 filled triangles for n = 2; and 13 filled triangles for n = 3; and so forth.

API specification. When writing your program, exercise modular design by organizing it into four functions, as specified in the following API:

public class Sierpinski {

    //  Height of an equilateral triangle whose sides are of the specified length.
    public static double height(double length)

    //  Draws a filled equilateral triangle whose bottom vertex is (x, y)
    //  of the specified side length.
    public static void filledTriangle(double x, double y, double length)

    //  Draws a Sierpinski triangle of order n, such that the largest filled
    //  triangle has bottom vertex (x, y) and sides of the specified length.
    public static void sierpinski(int n, double x, double y, double length)

    //  Takes an integer command-line argument n;
    //  draws the outline of an equilateral triangle (pointed upwards) of length 1;
    //  whose bottom-left vertex is (0, 0) and bottom-right vertex is (1, 0); and
    //  draws a Sierpinski triangle of order n that fits snugly inside the outline.
    public static void main(String[] args)
}

Restrictions: You may not change either the scale or size of the drawing window.

Part 3.   In this part you will create a program Art.java that produces a recursive drawing of your own design. It must take one integer command-line argument n that controls the depth of recursion. It must stay within the drawing window when n is between 1 and 7. It can be a geometric pattern, a random construction, or anything else that takes advantage of recursive functions. For full marks, it must not be something that could be easily rewritten to use loops in place of recursion, and some aspects of the recursive function-call tree (or how parameters or overlapping are used) must be distinct from the in-class examples (HTreeSierpinskiNestedCirclesBrownian).

Optionally, you may use the Transform2D library you implemented in Part 1. You may also define additional geometric transforms in Art.java, such as sheerreflect across the x– or y- axis, or rotate about an arbitrary point.

Additional requirements: Your program must be organized into at least three separate functions, including main(). All functions except main() must be private.

Restrictions: You may not change the size of the drawing window (but you may change the scale). Do not add sound.

Submission.   Submit Transform2D.javaSierpinski.java, and Art.java. If your Art.java requires any supplementary image files, submit them as well. Finally, submit a readme.txt file and answer the questions therein.

Challenge for the bored.   Write a program that plots Sierpinski triangles without using recursion.

Checklist:

https://java.mrseliasclasses.org/recursion-in-graphics-sierpinski-triangle-checklist/

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 Basics

  • Text and color. To annotate or highlight various elements in your drawings, StdDraw includes methods for drawing text, setting the font, and setting the ink in the pen.
  • In this code, java.awt.Font and java.awt.Color are abstractions that are implemented with non-primitive types that you will learn about in Section 3.1. Until then, we leave the details to StdDraw. The default ink color is black; the default font is a 16-point plain Serif font.
  • Double buffering. StdDraw supports a powerful computer graphics feature known as double buffering. When double buffering is enabled by calling enableDoubleBuffering(), all drawing takes place on the offscreen canvas. The offscreen canvas is not displayed; it exists only in computer memory. Only when you call show() does your drawing get copied from the offscreen canvas to the onscreen canvas, where it is displayed in the standard drawing window. You can think of double buffering as collecting all of the lines, points, shapes, and text that you tell it to draw, and then drawing them all simultaneously, upon request. One reason to use double buffering is for efficiency when performing a large number of drawing commands.
  • Computer animations. Our most important use of double buffering is to produce computer animations, where we create the illusion of motion by rapidly displaying static drawings. We can produce animations by repeating the following four steps:
    • Clear the offscreen canvas.
    • Draw objects on the offscreen
    • Copy the offscreen canvas to the onscreen canvas.
    • Wait for a short while. In support of these steps, the StdDraw has several methods:
    • Standard drawing animation commands

    • The “Hello, World” program for animation is to produce a black ball that appears to move around on the canvas, bouncing off the boundary according to the laws of elastic collision. Suppose that the ball is at position (xy) and we want to create the impression of having it move to a new position, say (x + 0.01, y + 0.02). We do so in four steps:
    • Clear the offscreen canvas to white.
    • Draw a black ball at the new position on the offscreen canvas.
    • Copy the offscreen canvas to the onscreen canvas.
    • Wait for a short while. To create the illusion of movement, BouncingBall.java iterates these steps for a whole sequence of positions of the ball.
    • Bouncing ball
  • 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). BouncingBallDeluxe.java illustrates an example where the bouncing ball is replaced by an image of a tennis ball.
  • 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.

Standard audio API

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.
    Musical notes, numbers, and waves
  • 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).
    Sampling a sine wave at various rates             Sampling a sine wave at 44,100 Hertz 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: 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