draw shapes on 3d plot matlab

1.5   Input and Output

In this department we extend the set of simple abstractions (command-line input and standard output) that we have been using as the interface between our Java programs and the exterior world to include standard input, standard drawing, and standard sound. Standard input makes it convenient for us to write programs that procedure capricious amounts of input and to interact with our programs; standard depict makes it possible for the states to work with graphics; and standard sound adds sound. Bird's eye view

Bird's-heart view.

A Java program takes input values from the control line and prints a string of characters as output. Past default, both control-line arguments and standard output are associated with an application that takes commands, which we refer to every bit the last window.

  • Command-line arguments. All of our classes accept a principal() method that takes a String array args[] as argument. That array is the sequence of command-line arguments that we type. If nosotros intend for an argument to be a number, we must utilise a method such as Integer.parseInt() to catechumen it from String to the appropriate type.
  • Standard output. To print output values in our programs, we have been using Organisation.out.println(). Java sends the results to an abstract stream of characters known as standard output. By default, the operating organisation connects standard output to the terminal window. All of the output in our programs and then far has been appearing in the terminal window.

RandomSeq.coffee uses this model: It takes a command-line argument n and prints to standard output a sequence of n random numbers between 0 and i.

To complete our programming model, we add together the following libraries:

  • Standard input. Read numbers and strings from the user.
  • Standard cartoon. Plot graphics.
  • Standard audio. Create audio.

Standard output.

Coffee's

Organization.out.print()

and

System.out.println()

methods implement the basic standard output abstraction that we demand. Nevertheless, to treat standard input and standard output in a compatible way (and to provide a few technical improvements), we use like methods that are defined in our StdOut library:

Standard output API

Java's

print()

and

println()

methods are the ones that yous accept been using. The

printf()

method gives us more control over the appearance of the output.

  • Formatted press basics. In its simplest form, printf() takes two arguments. The offset argument is called the format cord. It contains a conversion specification that describes how the second argument is to exist converted to a string for output.
    anatomy of printf() call
    Format strings begin with % and terminate with a one-alphabetic character conversion code. The following table summarizes the nigh frequently used codes:
    formatting examples for printf()
  • Format string. The format string can contain characters in addition to those for the conversion specification. The conversion specification is replaced past the argument value (converted to a string every bit specified) and all remaining characters are passed through to the output.
  • Multiple arguments. The printf() role can take more than two arguments. In this case, the format string will accept an boosted conversion specification for each additional argument.

Hither is more than documentation on printf format string syntax.

Standard input.

Our StdIn library takes data from a standard input stream that contains a sequence of values separated past whitespace. Each value is a string or a value from i of Java's primitive types. I of the key features of the standard input stream is that your plan consumes values when it reads them. Once your plan has read a value, it cannot dorsum upward and read it again. The library is defined by the following API:

Standard input API

We now consider several examples in detail.

  • Typing input. When you use the java control to invoke a Coffee plan from the command line, you actually are doing iii things: (1) issuing a command to start executing your programme, (2) specifying the values of the command-line arguments, and (iii) beginning to ascertain the standard input stream. The string of characters that you blazon in the terminal window after the command line is the standard input stream. For instance, AddInts.coffee takes a command-line statement n, and then reads n numbers from standard input and adds them, and prints the result to standard output:
    anatomy of a command
  • Input format. If you blazon abc or 12.2 or true when StdIn.readInt() is expecting an int, and so it volition respond with an InputMismatchException. StdIn treats strings of consecutive whitespace characters as identical to one space and allows y'all to circumscribe your numbers with such strings.
  • Interactive user input. TwentyQuestions.java is a simple example of a program that interacts with its user. The programme generates a random integer and then gives clues to a user trying to approximate the number. The primal difference between this program and others that we have written is that the user has the ability to change the control flow while the program is executing.
  • Processing an arbitrary-size input stream. Typically, input streams are finite: your plan marches through the input stream, consuming values until the stream is empty. But there is no restriction of the size of the input stream. Average.coffee reads in a sequence of real numbers from standard input and prints their average.

Redirection and piping.

For many applications, typing input data as a standard input stream from the terminal window is untenable because doing so limits our program's processing power by the amount of information that we can type. Similarly, nosotros often want to save the information printed on the standard output stream for later utilise. We can utilize operating organisation mechanisms to address both bug.

  • Redirecting standard output to a file. By calculation a simple directive to the command that invokes a program, nosotros can redirect its standard output to a file, either for permanent storage or for input to some other programme at a later time. For example, the command
    Redirecting standard output
    specifies that the standard output stream is not to be printed in the last window, but instead is to exist written to a text file named data.txt. Each telephone call to StdOut.print() or StdOut.println() appends text at the end of that file. In this instance, the end result is a file that contains i,000 random values.
  • Redirecting standard output from a file. Similarly, we can redirect standard input and so that StdIn reads information from a file instead of the terminal window. For example, the command
    Redirecting standard input
    reads a sequence of numbers from the file data.txt and computes their average value. Specifically, the < symbol is a directive to implement the standard input stream by reading from the file data.txt instead of by waiting for the user to type something into the last window. When the program calls StdIn.readDouble(), the operating system reads the value from the file. This facility to redirect standard input from a file enables the states to process huge amounts of data from whatever source with our programs, limited only by the size of the files that nosotros can store.
  • Connecting two programs. The most flexible way to implement the standard input and standard output abstractions is to specify that they are implemented by our ain programs! This machinery is chosen piping. For instance, the following command
    Piping
    specifies that the standard output for RandomSeq and the standard input stream for Average are the same stream.
  • Filters. For many common tasks, information technology is convenient to think of each program as a filter that converts a standard input stream to a standard output stream in some manner, RangeFilter.java takes ii command-line arguments and prints on standard output those numbers from standard input that fall within the specified range.

    Your operating system as well provides a number of filters. For example, the sort filter puts the lines on standard input in sorted order:

    %                  java RandomSeq 5 | sort                  0.035813305516568916  0.14306638757584322  0.348292877655532103  0.5761644592016527  0.9795908813988247                
    Another useful filter is more, which reads data from standard input and displays it in your terminal window i screenful at a time. For example, if y'all type
    %                  java RandomSeq 1000 | more                
    you will encounter as many numbers equally fit in your final window, but more will wait for you to hitting the space bar earlier displaying each succeeding screenful.

Standard cartoon.

Now we introduce a unproblematic brainchild for producing drawings equally output. We imagine an abstract drawing device capable of drawing lines and points on a two-dimensional canvas. The device is capable of responding to the commands that our programs issue in the form of calls to static methods in StdDraw. The main interface consists of two kinds of methods: drawing commands that crusade the device to take an action (such as cartoon a line or cartoon a betoken) and control commands that fix parameters such as the pen size or the coordinate scales.

  • Basic drawing commands. We starting time consider the drawing commands:
    Standard drawing API: drawing commands
    These methods are most self-documenting: StdDraw.line(x0, y0, x1, y1) draws a straight line segment connecting the point (10 0, y 0) with the point (x 1, y 1). StdDraw.point(ten, y) draws a spot centered on the point (10, y). The default coordinate calibration is the unit square (all x- and y-coordinates between 0 and 1). The standard implementation displays the canvass in a window on your computer's screen, with black lines and points on a white background.

    Your get-go drawing. The HelloWorld for graphics programming with StdDraw is to depict a triangle with a indicate inside. Triangle.java accomplishes this with iii calls to StdDraw.line() and one call to StdDraw.point().

  • Command commands. The default canvas size is 512-by-512 pixels and the default coordinate organization is the unit square, but we ofttimes want to describe plots at unlike scales. Besides, nosotros often want to draw line segments of dissimilar thickness or points of different size from the standard. To accommodate these needs, StdDraw has the post-obit methods:
    Standard drawing API: control commands
    For example, the ii-telephone call sequence
    StdDraw.setXscale(x0, x1); StdDraw.setYscale(y0, y1);                
    sets the drawing coordinates to exist within a bounding box whose lower-left corner is at (x 0, y 0) and whose upper-correct corner is at (x i, y one).
    • Filtering data to a standard drawing. PlotFilter.coffee reads a sequence of points defined past (x, y) coordinates from standard input and draws a spot at each point. Information technology adopts the convention that the showtime four numbers on standard input specify the bounding box, so that information technology can scale the plot.
      % java PlotFilter < USA.txt

      13509 cities in the US

    • Plotting a function graph. FunctionGraph.java plots the function y = sin(4ten) + sin(xxx) in the interval (0, π). At that place are an infinite number of points in the interval, and so nosotros have to make practise with evaluating the function at a finite number of points within the interval. Nosotros sample the function by choosing a set of x-values, so computing y-values by evaluating the part at each x-value. Plotting the function past connecting successive points with lines produces what is known as a piecewise linear approximation.
      Plotting a function graph
  • Outline and filled shapes. StdDraw besides includes methods to draw circles, rectangles, and arbitrary polygons. Each shape defines an outline. When the method proper name is just the shape proper noun, that outline is traced by the cartoon pen. When the method name begins with filled, the named shape is instead filled solid, not traced.
    Standard drawing API: shapes
    The arguments for circle() define a circle of radius r; the arguments for square() define a square of side length 2r centered on the given signal; and the arguments for polygon() define a sequence of points that we connect by lines, including ane from the terminal point to the starting time signal.
    Standard drawing shapes
  • Text and color. To annotate or highlight various elements in your drawings, StdDraw includes methods for drawing text, setting the font, and setting the the ink in the pen.
    Standard drawing text and color commands
    In this code, java.awt.Font and java.awt.Colour are abstractions that are implemented with not-primitive types that yous volition learn about in Section 3.1. Until so, nosotros leave the details to StdDraw. The default ink color is black; the default font is a xvi-point plain Serif font.
  • Double buffering. StdDraw supports a powerful computer graphics characteristic known as double buffering. When double buffering is enabled by calling enableDoubleBuffering(), all cartoon takes identify on the offscreen canvas. The offscreen canvas is not displayed; it exists merely in reckoner retentivity. Only when you telephone call testify() does your drawing go copied from the offscreen sail to the onscreen canvas, where information technology is displayed in the standard drawing window. You tin call up of double buffering as collecting all of the lines, points, shapes, and text that you tell it to depict, and so drawing them all simultaneously, upon request. One reason to use double buffering is for efficiency when performing a large number of drawing commands.
  • Estimator animations. Our near important employ of double buffering is to produce calculator animations, where we create the illusion of movement by rapidly displaying static drawings. We tin can produce animations by repeating the following iv steps:
    • Clear the offscreen canvass.
    • Describe objects on the offscreen
    • Re-create 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, Globe" program for blitheness 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 (ten, y) and nosotros want to create the impression of having it move to a new position, say (x + 0.01, y + 0.02). We do and 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 sail 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 equally well every bit geometric shapes. The control StdDraw.film(x, y, filename) plots the prototype in the given filename (either JPEG, GIF, or PNG format) on the sheet, centered on (x, y). BouncingBallDeluxe.java illustrates an example where the billowy ball is replaced by an paradigm of a tennis ball.
  • User interaction. Our standard draw library besides includes methods and so that the user can interact with the window using the mouse.
    double mouseX()          return ten-coordinate of mouse double mouseY()          return y-coordinate of mouse boolean mousePressed()   is the mouse currently being pressed?                
    • A first example. MouseFollower.coffee 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 push button, the brawl changes color from blue to cyan.
    • A uncomplicated attractor. OneSimpleAttractor.coffee 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 likewise accounts for a drag force. When the user clicks, the assurance disperse randomly.
    • Springs. Springs.java implements a spring system.

Standard audio.

StdAudio is a library that you lot can use to play and manipulate sound files. Information technology allows yous to play, manipulate and synthesize audio.

Standard audio API

Nosotros introduce some some basic concepts behind ane of the oldest and most important areas of computer science and scientific computing: digital bespeak processing.

  • Concert A. Concert A is a sine moving ridge, scaled to oscillate at a frequency of 440 times per second. The function sin(t) repeats itself once every 2π units on the x-centrality, then if we measure t in seconds and plot the function sin(2πt × 440) nosotros get a curve that oscillates 440 times per second. The aamplitude (y-value) corresponds to the volume. We assume information technology is scaled to exist between −1 and +one.
  • Other notes. A unproblematic 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 become the ithursday annotation above a given note by multiplying its frequency by the (i/12)th ability of 2.
    Musical notes, numbers, and waves
    When you lot double or halve the frequency, you move up or downwards an octave on the scale. For example 880 hertz is one octave above concert A and 110 hertz is ii octaves below concert A.
  • Sampling. For digital sound, we correspond a bend by sampling it at regular intervals, in precisely the same manner as when we plot function graphs. Nosotros sample sufficiently often that we have an accurate representation of the curve—a widely used sampling charge per unit is 44,100 samples per second. It is that simple: we stand for audio every bit an array of numbers (existent numbers that are between −i and +1).
    For example, the following lawmaking fragment plays concert A for ten seconds.
    int SAMPLING_RATE = 44100; double hz = 440.0; double duration = 10.0; int n = (int) (SAMPLING_RATE * duration); double[] a = new double[n+i]; for (int i = 0; i <= n; i++) {    a[i] = Math.sin(2 * Math.PI * i * hz / SAMPLING_RATE);  } StdAudio.play(a);                
  • Play that melody. PlayThatTune.java is an example that shows how hands nosotros tin create music with StdAudio. It takes notes from standard input, indexed on the chromatic scale from concert A, and plays them on standard audio.

Exercises

  1. Write a program MaxMin.java that reads in integers (as many equally the user enters) from standard input and prints out the maximum and minimum values.
  2. Write a programme Stats.java that takes an integer command-line statement n, reads northward floating-point numbers from standard input, and prints their mean (boilerplate value) and sample standard deviation (foursquare root of the sum of the squares of their differences from the average, divided by northward−ane).
  3. Write a program LongestRun.java that reads in a sequence of integers and prints out both the integer that appears in a longest consecutive run and the length of the run. For example, if the input is 1 2 2 i five 1 i vii 7 seven 7 ane 1, then your program should impress Longest run: four consecutive 7s.
  4. Write a program WordCount.java that reads in text from standard input and prints out the number of words in the text. For the purpose of this practise, a word is a sequence of non-whitespace characters that is surrounded past whitespace.
  5. Write a program Closest.java that takes three floating-point command-line arguments \(x, y, z\), reads from standard input a sequence of point coordinates \((x_i, y_i, z_i)\), and prints the coordinates of the bespeak closest to \((x, y, z)\). Call up that the square of the altitude between \((ten, y, z)\) and \((x_i, y_i, z_i)\) is \((x - x_i)^2 + (y - y_i)^ii + (z - z_i)^2\). For efficiency, exercise non employ Math.sqrt() or Math.pow().
  6. Given the positions and masses of a sequence of objects, write a program to compute their eye-of-mass or centroid. The centroid is the average position of the due north objects, weighted past mass. If the positions and masses are given by (xi , yi , grandi ), and so the centroid (ten, y, yard) is given by:
    g  =                  yard1                                    +                  thousand2                                    + ... +                  mdue north                                    x  = (m1teni                                    +  ... +                  mnorthxn                  ) / m y  = (maney1                                    +  ... +                  1000nyn                  ) / m                

    Write a plan Centroid.java that reads in a sequence of positions and masses (xi , yi , grandi ) from standard input and prints out their center of mass (ten, y, m). Hint: model your plan afterward Average.java.

  7. Write a program Checkerboard.java that takes a control-line argument north and plots an n-by-due north checkerboard with red and black squares. Color the lower-left square red.
  8. Write a program Rose.coffee that takes a command-line argument n and plots a rose with due north petals (if north is odd) or 2n petals (if north is even) by plotting the polar coordinates (r, θ) of the function r = sin(n × θ) for θ ranging from 0 to 2π radians. Below is the desired output for northward = 4, vii, and viii.

    rose

  9. Write a program Banner.java that takes a string s from the command line and display information technology in banner way on the screen, moving from left to right and wrapping back to the beginning of the cord as the stop is reached. Add a second command-line argument to control the speed.
  10. Write a plan Circles.coffee that draws filled circles of random size at random positions in the unit square, producing images like those below. Your program should take four command-line arguments: the number of circles, the probability that each circle is black, the minimum radius, and the maximum radius.
    random circles

Creative Exercises

  1. Spirographs. Write a program Spirograph.java that takes 3 command-line arguments R, r, and a and draws the resulting spirograph. A spirograph (technically, an epicycloid) is a curve formed by rolling a circle of radius r effectually a larger fixed circumvolve or radius R. If the pen outset from the center of the rolling circumvolve is (r+a), and so the equation of the resulting curve at time t is given by
    x(t) = (R+r)*cos(t) - (r+a)*cos(((R+r)/r)*t) y(t) = (R+r)*sin(t) - (r+a)*sin(((R+r)/r)*t)                

    Such curves were popularized by a acknowledged toy that contains discs with gear teeth on the edges and small holes that you could put a pen in to trace spirographs.

    For a dramatic 3d result, describe a circular paradigm, east.k., earth.gif instead of a dot, and show it rotating over time. Here's a picture of the resulting spirograph when R = 180, r = twoscore, and a = 15.

  2. Clock. Write a program Clock.java that displays an animation of the second, infinitesimal, and hour hands of an analog clock. Use the method StdDraw.show(1000) to update the display roughly one time per 2nd.

    Hint: this may be i of the rare times when y'all desire to use the % operator with a double - it works the style yous would await.

  3. Oscilloscope. Write a program Oscilloscope.java to simulate the output of an oscilloscope and produce Lissajous patterns. These patterns are named after the French physicist, Jules A. Lissajous, who studied the patterns that arise when 2 mutually perpendicular periodic disturbances occur simultaneously. Presume that the inputs are sinusoidal, and so tha the following parametric equations depict the curve:
    x = Ax sin (westwardxt + θx) y = Ay sin (due westyt + θy) Ax, Ay = amplitudes wx, wy                  = angular velocity θten, θy                  = phase factors                

    Accept the six parameters Aten, due westx, θten, θy, wy, and θy from the command line.

    For example, the offset image below has Ax = Ay = one, w10 = 2, wy = 3, θten = twenty degrees, θy = 45 degrees. The other has parameters (1, 1, 5, 3, 30, 45)

Web Exercises

  1. Discussion and line count. Change WordCount.java and then that reads in text from standard input and prints out the number of characters, words, and lines in the text.
  2. Rainfall problem. Write a program Rainfall.coffee that reads in nonnegative integers (representing rainfall) i at a fourth dimension until 999999 is entered, and so prints out the average of value (non including 999999).
  3. Remove duplicates. Write a program Duplicates.java that reads in a sequence of integers and prints back out the integers, except that it removes repeated values if they appear consecutively. For example, if the input is 1 two 2 1 5 1 1 seven vii 7 7 i 1, your program should impress out ane 2 1 5 1 7 ane.
  4. Run length encoding. Write a plan RunLengthEncoder.java that encodes a binary input using run length encoding. Write a program RunLengthDecoder.coffee that decodes a run length encoded message.
  5. Caput and tail. Write programs Head.java and Tail.java that have an integer command line input N and print out the start or last N lines of the given file. (Print the whole file if it consists of <= N lines of text.)
  6. Impress a random word. Read a list of N words from standard input, where N is unknown ahead of time, and impress out 1 of the N words uniformly at random. Do not store the discussion list. Instead, use Knuth's method: when reading in the ith give-and-take, select it with probability 1/i to be the selected word, replacing the previous champion. Print out the word that survives afterward reading in all of the data.
  7. Caesar nada. Julius Caesar sent secret messages to Cicero using a scheme that is at present known equally a Caesar cipher. Each alphabetic character is replaced by the letter k positions ahead of it in the alphabet (and y'all wrap around if needed). The table below gives the Caesar cipher when k = 3.
    Original:  A B C D East F G H I J Chiliad L Chiliad North O P Q R S T U V W X Y Z Caesar:    D Eastward F G H I J K L Yard N O P Q R Due south T U 5 W Ten Y Z A B C                

    For example the message "VENI, VIDI, VICI" is converted to "YHQL, YLGL, YLFL". Write a program Caesar.coffee that takes a command-line statement m and applies a Caesar cipher with shift = thou to a sequence of messages read from standard input. If a letter is not an uppercase alphabetic character, simply print it back out.

  8. Caesar cypher decoding. How would yous decode a bulletin encrypted using a Caesar cipher? Hint: you should not need to write any more lawmaking.
  9. Parity check. A Boolean matrix has the parity belongings when each row and each column has an even sum. This is a simple type of error-correcting code because if ane scrap is corrupted in transmission (bit is flipped from 0 to 1 or from 1 to 0) information technology can exist detected and repaired. Here's a 4 10 four input file which has the parity property:
    1 0 one 0 0 0 0 0 ane i i i 0 one 0 1                

    Write a program ParityCheck.java that takes an integer Due north as a command line input and reads in an N-by-N Boolean matrix from standard input, and outputs if (i) the matrix has the parity property, or (two) indicates which single corrupted scrap (i, j) can be flipped to restore the parity holding, or (iii) indicates that the matrix was corrupted (more than two bits would need to be changed to restore the parity property). Employ equally little internal storage as possible. Hint: you do not fifty-fifty have to store the matrix!

  10. Takagi's office. Plot Takagi's function: everywhere continuous, nowhere differentiable.
  11. Hitchhiker problem. You lot are interviewing N candidates for the sole position of American Idol. Every minute yous get to see a new candidate, and yous have one minute to make up one's mind whether or non to declare that person the American Idol. You may not change your mind once you stop interviewing the candidate. Suppose that you can immediately rate each candidate with a single existent number betwixt 0 and 1, but of course, yous don't know the rating of the candidates non yet seen. Devise a strategy and write a program AmericanIdol that has at least a 25% chance of picking the best candidate (assuming the candidates arrive in random social club), reading the 500 data values from standard input.

    Solution: interview for Due north/2 minutes and record the rating of the best candidate seen so far. In the next N/2 minutes, option the outset candidate that has a college rating than the recorded one. This yields at to the lowest degree a 25% chance since y'all will get the all-time candidate if the second best candidate arrives in the get-go Due north/2 minutes, and the best candidate arrives in the terminal Northward/2 minutes. This can be improved slightly to one/e = 0.36788 by using essentially the same strategy, but switching over at fourth dimension Northward/eastward.

  12. Nested diamonds. Write a program Diamonds.java that takes a command line input Due north and plots North nested squares and diamonds. Below is the desired output for Northward = three, 4, and five.
  13. Regular polygons. Create a role to plot an Northward-gon, centered on (x, y) of size length s. Use the office to draws nested polygons like the picture below.
    nested polygons
  14. Bulging squares. Write a programme BulgingSquares.java that draws the following optical illusion from Akiyoshi Kitaoka The centre appears to bulge outwards even though all squares are the aforementioned size.
    bulging squares
  15. Spiraling mice. Suppose that N mice that start on the vertices of a regular polygon with North sides, and they each head toward the nearest other mouse (in counterclockwise management) until they all meet. Write a program to draw the logarithmic spiral paths that they trace out by drawing nested N-gons, rotated and shrunk as in this animation.
  16. Spiral. Write a program to draw a spiral like the one beneath.

    spiral

  17. Earth. Write a plan Globe.java that takes a real command-line argument α and plots a globe-similar pattern with parameter α. Plot the polar coordinates (r, θ) of the function f(θ) = cos(α × θ) for θ ranging from 0 to 7200 degrees. Beneath is the desired output for α = 0.8, 0.nine, and 0.95.
  18. Drawing strings. Write a program RandomText.java that takes a string s and an integer Due north as control line inputs, and writes the cord N times at a random location, and in a random color.
  19. 2D random walk. Write a program RandomWalk.java to simulate a second random walk and animate the results. Start at the center of a 2N-by-2N grid. The current location is displayed in blue; the trail in white.
    random walk in 2d after 5 steps random 2d walk after 25 steps random 2d walk after 106 steps
  20. Rotating table. You are seated at a rotating square table (like a lazy Susan), and in that location are iv coins placed in the four corners of the tabular array. Your goal is to flip the coins so that they are either all heads or all tails, at which point a bell rings to notify you that y'all are done. You lot may select any two of them, make up one's mind their orientation, and (optionally) flip either or both of them over. To make things challenging, you are blindfolded, and the table is spun afterward each time you select two coins. Write a plan RotatingTable.java that initializes the coins to random orientations. Then, it prompts the user to select two positions (ane-4), and identifies the orientation of each money. Side by side, the user tin can specify which, if whatsoever of the ii coins to flip. The process repeats until the user solves the puzzle.
  21. Rotating table solver. Write another plan RotatingTableSolver.java to solve the rotating table puzzle. I effective strategy is to choose ii coins at random and flip them to heads. Yet, if you get really unlucky, this could take an capricious number of steps. Goal: devise a strategy that always solves the puzzle in at most five steps.
  22. Hex. Hex is a ii-player board game popularized by John Nash while a graduate educatee at Princeton University, and after commercialized by Parker Brothers. It is played on a hexagonal grid in the shape of an eleven-by-xi diamond. Write a program Hex.coffee that draws the board.
  23. Projectile motion with drag. Write a programme BallisticMotion.java that plots the trajectory of a brawl that is shot with velocity v at an angle theta. Business relationship for gravitational and drag forces. Assume that the elevate strength is proportional to the square of the velocity. Using Newton's equations of motions and the Euler-Cromer method, update the position, velocity, and dispatch according to the post-obit equations:
    v  = sqrt(vx*vx + vy*vy)  ax = - C * v * vx          ay = -M - C * v * vy vx = vx + ax * dt          vy = vy + ay * dt  x =  x + vx * dt           y =  y + vy * dt                

    Use G = ix.viii, C = 0.002, and set the initial velocity to 180 and the angle to sixty degrees.

  24. Heart. Write a program Heart.java to draw a pink eye: Depict a diamond, then describe two circles to the upper left and upper right sides.
    Heart
  25. Changing square. Write a program that draws a square and changes its color each second.
  26. Uncomplicated harmonic movement. Repeat the previous practice, but animate the Lissajous patterns as in this applet. Ex: A = B = westward10 = wy = 1, simply at each time t draw 100 (or so) points with φten ranging from 0 to 720 degrees, and φx ranging from 0 to 1080 degrees.
  27. Bresenham's line drawing algorithm. To plot a line segment from (x1, y1) to (x2, y2) on a monitor, say 1024-by-1024, you need to make a discrete approximation to the continuous line and determine exactly which pixels to turn on. Bresenham'due south line drawing algorithm is a clever solution that works when the gradient is between 0 and 1 and x1 < x2.
    int dx  = x2 - x1; int dy  = y2 - y1; int y   = y1; int eps = 0;      for (int x = x1; ten <= x2; x++) {     StdDraw.point(x, y);     eps += dy;     if (2*eps >= dx)  {        y++;        eps -= dx;     } }                
  28. Modify Bresenham'southward algorithm to handle arbitrary line segments.
  29. Miller's madness. Write a program Madness.java to plot the parametric equation:
    x = sin(0.99 t) - 0.7 cos( iii.01 t) y = cos(i.01 t) + 0.1 sin(xv.03 t)                
    where the parameter t is in radians. You should get the following complex motion-picture show. Experiment by changing the parameters and produce original pictures.
  30. Fay's butterfly. Write a programme Butterfly.java to plot the polar equation:
    r = east^(cos t) - two cos(4t) + (sin(t/12)^five)                
    where the parameter t is in radians. You should get an image like the following butterfly-like effigy. Experiment past changing the parameters and produce original pictures.
    Butterfly
  31. Pupil database. The file students.txt contains a listing of students enrolled in an introductory informatics class at Princeton. The kickoff line contains an integer North that specifies the number of students in the database. Each of the next N lines consists of four pieces of information, separated by whitespace: start name, last name, email address, and section number. The program Students.java reads in the integer North and and then Due north lines of data of standard input, stores the information in four parallel arrays (an integer assortment for the section number and cord arrays for the other fields). And so, the plan prints out a list of students in department 4 and 5.
  32. Shuffling. In the Oct 7, 2003 California state runoff ballot for governor, in that location were 135 official candidates. To avert the natural prejudice against candidates whose names announced at the terminate of the alphabet (Jon W. Zellhoefer), California election officials sought to order the candidates in random social club. Write a programme plan Shuffle.java that takes a command-line statement North, reads in Due north strings from standard input, and prints them back out in shuffled club. (California decided to randomize the alphabet instead of shuffling the candidates. Using this strategy, not all N! possible outcomes are as probable or even possible! For example, two candidates with very like concluding names will always end up next to each other.)
  33. Reverse. Write a program Reverse.coffee that reads in an capricious number of existent values from standard input and prints them in reverse club.
  34. Fourth dimension series analysis. This trouble investigates two methods for forecasting in time series analysis. Moving average or exponential smoothing.
  35. Polar plots. Create any of these polar plots.
  36. Coffee games. Use StdDraw.java to implement one of the games at javaunlimited.net.
  37. Consider the post-obit programme.
    public class Mystery {    public static void main(String[] args) {       int N = Integer.parseInt(args[0]);       int[] a = new int[M];        while(!StdIn.isEmpty()) {          int num = StdIn.readInt();          a[num]++;       }        for (int i = 0; i < Grand; i++)          for (int j = 0; j < a[i]; j++)             Arrangement.out.print(i + " ");       Organization.out.println();    } }              

    Suppose the file input.txt contains the following integers:

    8 8 3 five 1 vii 0 9 2 half dozen 9 7 4 0 v iii nine three vii 6              

    What is the contents of the array a after running the following control

    java Mystery x < input.txt              
  38. High-low. Shuffle a deck of cards, and deal one to the player. Prompt the player to approximate whether the next card is higher or lower than the current carte. Repeat until player guesses it wrong. Game show: ???? used this.
  39. Elastic collisions. Write a program CollidingBalls.java that takes a command-line argument n and plots the trajectories of n billowy balls that bounce of the walls and each other according to the laws of rubberband collisions. Assume all the assurance accept the same mass.
  40. Elastic collisions with obstacles. Each ball should have its own mass. Put a large ball in the center with goose egg initial velocity. Brownian motion.
  41. Statistical outliers. Modify Average.java to print out all the values that are larger than ane.5 standard deviations from the mean. You will need an assortment to shop the values.
  42. Optical illusions. Create a Kofka ring or one of the other optical illusions collected past Edward Adelson.
  43. Computer animation. In 1995 James Gosling presented a demonstration of Java to Sun executives, illustrating its potential to deliver dynamic and interactive Web content. At the time, web pages were stock-still and non-interactive. To demonstrate what the Web could be, Gosling presented applets to rotate 3D molecules, visualize sorting routines, and Duke cart-wheeling across the screen. Coffee was officially introduced in May 1995 and widely adopted in the technology sector. The Internet would never be the same.
    Duke doing cartwheels
    Plan Duke.java reads in the 17 images T1.gif through T17.gif and produces the animation. To execute on your calculator, download the 17 GIF files and put in the same directory as Duke.java. (Alternatively, download and unzip the file duke.nix or knuckles.jar to extract all 17 GIFs.)
  44. Cart-wheeling Knuckles. Modify Duke.java then that it cartwheels 5 times across the screen, from correct to left, wrapping effectually when it hits the window boundary. Echo this cart-wheeling cycle 100 times. Hint: afterwards displaying a sequence of 17 frames, move 57 pixels to the left and repeat. Name your program MoreDuke.java.
  45. Tac (cat backwards). Write a program Tac.java that reads lines of text from standard input and prints the lines out in contrary order.
  46. Game. Implement the game dodge using StdDraw: move a blue disc within the unit square to bear on a randomly placed dark-green disc, while avoiding the moving cerise discs. After each touch, add a new moving red disc.
  47. Unproblematic harmonic motion. Create an animation like the one beneath from Wikipedia of simple harmonic motion.

    Simple harmonic motion

  48. Yin yang. Draw a yin yang using StdDraw.arc().
  49. Xx questions. Write a program QuestionsTwenty.java that plays xx questions from the opposite point of view: the user thinks of a number between ane and a one thousand thousand and the computer makes the guesses. Use binary search to ensure that the computer needs at most 20 guesses.
  50. Write a program DeleteX.java that reads in text from standard input and deletes all occurrences of the letter X. To filter a file and remove all X's, run your program with the following command:
    %                  java DeleteX < input.txt > output.txt                
  51. Write a programme ThreeLargest.coffee that reads integers from standard input and prints out the three largest inputs.
  52. Write a program Pnorm.coffee that takes a command-line argument p, reads in real numbers from standard input, and prints out their p-norm. The p-norm norm of a vector (xone, ..., xN) is divers to be the pth root of (|x1|p + |x2|p + ... + |xDue north|p).
  53. Consider the post-obit Coffee program.
    public class Mystery {    public static void principal(Cord[] args) {       int i = StdIn.readInt();       int j = StdIn.readInt();       System.out.println((i-ane));       System.out.println((j*i));    } }                

    Suppose that the file input.txt contains

    What does the post-obit control practice?
  54. Repeat the previous do simply utilize the following command instead
    java Mystery < input.txt | coffee Mystery | java Mystery | java Mystery                
  55. Consider the following Java program.
    public grade Mystery {    public static void main(String[] args) {       int i = StdIn.readInt();       int j = StdIn.readInt();       int k = i + j;       Organisation.out.println(j);       System.out.println(k);    } }                

    Suppose that the file input.txt contains the integers one and i. What does the following command do?

    coffee Mystery < input.txt | coffee Mystery | java Mystery | coffee Mystery                
  56. Consider the Java program Ruler.java.
    public class Ruler {     public static void main(String[] args) {        int n = StdIn.readInt();       String south = StdIn.readString();       Organisation.out.println((northward+ane) + " " + s + (n+1)  + s);    } }                

    Suppose that the file input.txt contains the integers 1 and one. What does the post-obit control do?

    java Ruler < input.txt | java Ruler | java Ruler | java Ruler                
  57. Modify Add.java so that it re-asks the user to enter two positive integers if the user types in a not-positive integer.
  58. Alter TwentyQuestions.java so that it re-asks the user to enter a response if the user types in something other than true or faux. Hint: add together a do-while loop within the main loop.
  59. Nonagram. Write a program to plot a nonagram.
  60. Star polygons. Write a program StarPolygon.java that takes 2 command line inputs p and q, and plots the {p/q}-star polygon.
  61. Complete graph. Write a program to plot that takes an integer N, plots an N-gon, where each vertex lies on a circle of radius 256. Then draw a grey line connecting each pair of vertices.
  62. Necker cube. Write a program NeckerCube.coffee to plot a Necker cube.
  63. What happens if you motility the StdDraw.clear(Colour.BLACK) command to before the beginning of the while loop in BouncingBall.java? Answer: attempt it and observe a prissy woven 3d design with the given starting velocity and position.
  64. What happens if you change the parameter of StdDraw.show() to 0 or g in BouncingBall.coffee?
  65. Write a program to plot a circular ring of width 10 like the one below using two calls to StdDraw.filledCircle().
  66. Write a program to plot a round ring of width 10 similar the one beneath using a nested for loop and many calls to StdDraw.signal().
  67. Write a programme to plot the Olympic rings.
    Olympic rings http://www.janecky.com/olympics/rings.html
  68. Write a program BouncingBallDeluxe.java that embellishes BouncingBall.java by playing a sound effect upon collision with the wall using StdAudio and the audio file pipebang.wav.

owensbyobsed1973.blogspot.com

Source: https://introcs.cs.princeton.edu/java/15inout/

0 Response to "draw shapes on 3d plot matlab"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel