Monthly Archives: September 2020

Input/Output: Graphics and Arrays: A Bar graph – Tracing

Let’s do some tracing with a smaller set of positive integers.

raw data array
{4,5,6,5,5,12,4,5,4,5,4,4,11,5,…} 100 random positive integers of range 1 to 20 inclusive

the goal in this assignment is to have the least number of “if” statements (if any at all)

the counter array initialy all elements are equal to ZERO — this is an array of 20 elements
counter array
{0,0,1,0,5,5,….} this is going to be the height of the rectangle

i: 0 –> 20 barCounter[0,0,0,0,0,0,0,0,0,..]

barCounter[rawData[i]]++

i = 0
rawData[0] –> 4
barCounter[rawData[0]]++
barCounter[4]++ –> 1 barCounter[0,0,0,0,1,0,0,0,0,..]

i = 1
rawData[1] –> 5
barCounter[rawData[1]]++
barCounter[5]++ –> 1 barCounter[0,0,0,0,1,1,0,0,0,..]

i = 2
rawData[2] –> 6
barCounter[rawData[2]]++
barCounter[6]++ –> 1 barCounter[0,0,0,0,1,1,1,0,0,..]


i = 3
rawData[3] –> 5
barCounter[rawData[3]]++
barCounter[5]++ –> 2 barCounter[0,0,0,0,1,2,1,0,0,..]

i = 4
rawData[4] –> 5

barCounter[5]++ –> 3 barCounter[0,0,0,0,1,3,1,0,0,..]

i = 20 [0,1,0,0,1,6,9,0,18,19,17……,1,1] // height of
//each rectangle
// the index is the x coordinate of the bargraph rectangle
for ( int i = 0; i < 100; i++)
barCounter[rawData[i]]++;

for loop to draw the rectangles where x is the index of barCounter array
and y is the value of the array barCounter with index x

// a short program to trace it with print statements
public class bargraph0
{
    public static void main(String [] args)
    {
        int raw = 0;
        int counter =0;
      int [] rawData = {4,5,6,5,5,12,4,5,4,5,4,4,11,5};
      int [] barCounter = new int[13]; // since 12 is the max value
      for ( int i = 0; i < rawData.length; i++)
      {
          System.out.println("i " + i + " rawData " + rawData[i]);
            barCounter[rawData[i]]++;
            raw = rawData[i];
            counter = barCounter[rawData[i]];
            System.out.println("barCounter array");
            for ( int j = 0; j < barCounter.length; j++)
            {
                System.out.print(barCounter[j] + " ");
            }
            System.out.println();
        }
    }
    
}
Take a look at the output:
Inital  state of the barCounter array
0 0 0 0 0 0 0 0 0 0 0 0 0 
Loop with i from 0 to 13
i 0 rawData 4
barCounter array
0 0 0 0 1 0 0 0 0 0 0 0 0 
i 1 rawData 5
barCounter array
0 0 0 0 1 1 0 0 0 0 0 0 0 
i 2 rawData 6
barCounter array
0 0 0 0 1 1 1 0 0 0 0 0 0 
i 3 rawData 5
barCounter array
0 0 0 0 1 2 1 0 0 0 0 0 0 
i 4 rawData 5
barCounter array
0 0 0 0 1 3 1 0 0 0 0 0 0 
i 5 rawData 12
barCounter array
0 0 0 0 1 3 1 0 0 0 0 0 1 
i 6 rawData 4
barCounter array
0 0 0 0 2 3 1 0 0 0 0 0 1 
i 7 rawData 5
barCounter array
0 0 0 0 2 4 1 0 0 0 0 0 1 
i 8 rawData 4
barCounter array
0 0 0 0 3 4 1 0 0 0 0 0 1 
i 9 rawData 5
barCounter array
0 0 0 0 3 5 1 0 0 0 0 0 1 
i 10 rawData 4
barCounter array
0 0 0 0 4 5 1 0 0 0 0 0 1 
i 11 rawData 4
barCounter array
0 0 0 0 5 5 1 0 0 0 0 0 1 
i 12 rawData 11
barCounter array
0 0 0 0 5 5 1 0 0 0 0 1 1 
i 13 rawData 5
barCounter array
0 0 0 0 5 6 1 0 0 0 0 1 1 
i 0 rawData 4
barCounter array
0 0 0 0 1 0 0 0 0 0 0 0 0 
i 1 rawData 5
barCounter array
0 0 0 0 1 1 0 0 0 0 0 0 0 
i 2 rawData 6
barCounter array
0 0 0 0 1 1 1 0 0 0 0 0 0 
i 3 rawData 5
barCounter array
0 0 0 0 1 2 1 0 0 0 0 0 0 
i 4 rawData 5
barCounter array
0 0 0 0 1 3 1 0 0 0 0 0 0 
i 5 rawData 12
barCounter array
0 0 0 0 1 3 1 0 0 0 0 0 1 
i 6 rawData 4
barCounter array
0 0 0 0 2 3 1 0 0 0 0 0 1 
i 7 rawData 5
barCounter array
0 0 0 0 2 4 1 0 0 0 0 0 1 
i 8 rawData 4
barCounter array
0 0 0 0 3 4 1 0 0 0 0 0 1 
i 9 rawData 5
barCounter array
0 0 0 0 3 5 1 0 0 0 0 0 1 
i 10 rawData 4
barCounter array
0 0 0 0 4 5 1 0 0 0 0 0 1 
i 11 rawData 4
barCounter array
0 0 0 0 5 5 1 0 0 0 0 0 1 
i 12 rawData 11
barCounter array
0 0 0 0 5 5 1 0 0 0 0 1 1 
i 13 rawData 5
barCounter array
0 0 0 0 5 6 1 0 0 0 0 1 1 
Final state of the barCounter array.

Input/Output: printf

 

Java’s print() and println() methods are the ones that you have been using. The printf() method gives us more control over the appearance of the output.

  • Formatted printing basics. In its simplest form, printf() takes two arguments. The first argument is called the format string. It contains a conversion specification that describes how the second argument is to be converted to a string for output.

Format strings begin with % and end with a one-letter conversion code. The following table summarizes the most frequently used codes:

  • Format string. The format string can contain characters in addition to those for the conversion specification. The conversion specification is replaced by the argument value (converted to a string as specified) and all remaining characters are passed through to the output.
  • Multiple arguments. The printf() function can take more than two arguments. In this case, the format string will have an additional conversion specification for each additional argument.

Here is more documentation on printf format string syntax

[spoiler title=’TestPrintf’]

public class TestPrintf
{
   public static void main(String [] args)
   {
       System.out.println("123456789012345678901234567890");
       System.out.printf("%10.2f%8.2f",3.33333, 1234.5677865);
       System.out.println();
       for (int i = 0; i < 12; i++){
        System.out.printf("%2d%6d",i, i*i);
        System.out.println();
    }
        
    }
}

/**
123456789012345678901234567890
      3.33 1234.57
 0     0
 1     1
 2     4
 3     9
 4    16
 5    25
 6    36
 7    49
 8    64
 9    81
10   100
11   121

 */

[/spoiler]

 

Input/Output: Graphics: Hex. Hex is a two-player board game

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

NOTE: INCLUDE GOOD DOCUMENTATION IN YOUR PROGRAMS
Classwork:
Standard Drawing: Animation and images Images.

  1. Hex. Hex is a two-player board game popularized by John Nash while a graduate student at Princeton University, and later commercialized by Parker Brothers. It is played on a hexagonal grid in the shape of an 11-by-11 diamond Write a program Hex.java that draws the board.

Screen Shot 2016-01-06 at 6.27.23 PM

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