CSE1030 Week 02 Homework Problems

Using Non-static Features in Classes

Short Problems

1. Create a StopWatch class that allows a client to measure the amount of time that has passed since the creation of the stopwatch. The class should have one long attribute that stores the time at which the stopwatch was created. The default constructor should set this attribute using java.lang.currentTimeMillis() or java.lang.nanoTime(). Finally, there should be at least one method that returns the time that has passed since the creation of the stopwatch; you might want several methods that return the elapsed time using different units (e.g., nanoseconds, microseconds, milliseconds, and seconds, for example).

This sort of class can be useful for timing how long parts of your code take to run:

StopWatch t = new StopWatch();

// some code that you want to time here

long millis = t.elapsedMillis();   // elapsed time in milliseconds
long micros = t.elapsedMicros();   // elapsed time in microseconds

 

2. Use your StopWatch class to compare the performance of using string concatenation versus StringBuilder to create long strings one character at a time:

final int N = 10000;
String s = "";
StopWatch t = new StopWatch();
for (int i = 0; i < N; i++) {
  s = s + 'a';
}
System.out.println(t.elapsedMicros());
final int N = 10000;
StringBuilder b = new StringBuilder("");
StopWatch t = new StopWatch();
for (int i = 0; i < N; i++) {
  b.append('a');
}
System.out.println(t.elapsedMicros());

Try values of N equal to 10000, 20000, 30000, ..., 100000 and plot the results.

3. Implement a class named Location that represents a position on the Earth's surface using latitude and longitude.

Latitude is measured in degrees and specifies the north-south position of a point on the Earth's surface. The range of valid angles is from -90 degrees (South pole) to +90 degrees (North pole).

Longitude is measured in degrees and specifies the east-west position of a point on the Earth's surface relative to the Prime Meridian. The range of valid angles is from -180 degrees (westward of the Prime Meridian) to +180 degrees (eastward of the Prime Meridian).

Your class should provide appropriate constructors, accessors, and mutators. You may need to validate the arguments to your constructors and mutators to ensure that they are valid latitude and longitude values. You might consider implementing equals and hashCode as well.

Moderate Problems

1. The stopwatch class described above is useful for timing a single event; if you want to time a second separate event, you need to create a new StopWatch object because you have no way of resetting a stopwatch. Modify the StopWatch class by adding a method that lets a client reset the stopwatch so that it can time subsequent events.

StopWatch t = new StopWatch();

// some code that you want to time here

long elapsed = t.elapsedMillis();   // elapsed time in milliseconds

// some code here that you do not want to time

// reset the stopwatch just before some code that you want to time
t.reset();

// some code that you want to time here

elapsed = t.elapsedMillis();

 

2. Modify the StopWatch class so that you can stop and start the stopwatch. The elapsed time recorded by the stopwatch includes only the elapsed time where the stopwatch was actually running.

StopWatch t = new StopWatch();

// some code that you want to time here that takes 5ms

long elapsed = t.elapsedMillis();   // approx. 5ms
t.stop();

// some code here that you do not want to time such as user input

// restart the stopwatch just before some code that you want to time
t.start();

// some code that you want to time here that takes 8 ms

elapsed = t.elapsedMillis();        // approx. 13ms 

 

3. Implement a class named Deck that represents a standard 52-card deck of playing cards (use the PlayingCard class from the Week 4 lab). The default constructor should create the deck of 52 (unique) cards. There should be a method named deal that deals one card from the top of the deck (i.e., the method removes the top card from the deck and returns it to the client). There should be a method named take that accepts a card and adds it to the bottom of the deck; however, the method should throw an exception if the card is already in the deck. Finally, there should be a method named shuffle that shuffles the deck (i.e., reorders the cards randomly).

 

4. Implement the type.lib.Fraction class from CSE1020 (API is here). The class has many features; you may want to implement only a subset of them (for example, ignore all of the static attributes and methods).

 

5. Implement a class named Dictionary that represents a dictionary of words. There should be a constructor that accepts a string that is the name of a file containing a list of words to put into the dictionary; the constructor needs to read the file to create the dictionary. There should be a method named lookUp that checks to see if a given string is in the dictionary and returns true if the string is in the dictionary, and false otherwise.

A text file containing 80368 English words (one on each line) can be found here.

 

6. Turtle graphics is a method for drawing geometric primitives (such as points, lines, and curves) in the Cartesian (xy) plane. Logo was one of the early computer languages designed for educational purposes, and it had turtle graphics as one of its main features.

In turtle graphics, the client has control of a cursor (the turtle) that responds to commands such as "move forward 1.5 units", "turn right", "turn left", and "turn 45 degrees". As the turtle moves, it leaves behind a trail using a pen; the pen can have attributes such as colour and radius to control the trail colour and thickness.

The turtle needs attributes to represent its position in the plane and the direction that it is facing. The position can be represented as x and y coordinates, and the direction can be represented as an angle between 0.0 and 360.0 degrees (measured counterclockwise from the positive x axis).

Implement a Turtle class that supports turtle graphics. Use the code shown below to start your program. The code below uses the StdDraw class from the textbook Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. StdDraw provides the capability to easily create simple drawings in a Java program. StdDraw uses an Cartesian coordinate system with the bottom left corner of the window having coordinates (0.0, 0.0) and the top right corner of the window having coordinates (1.0, 1.0). The API for StdDraw can be found here. The jar file containing StdDraw can be found here.

package cse1030;

import princeton.introcs.StdDraw;
import java.awt.Color;

public class Turtle {
  private double pX;
  private double pY;
  private double angle;
  private Color penColor;
  
  public Turtle() {
    // set position to (0.0, 0.0), angle to 0.0 degrees, and pen color to black
  }
  
  public Turtle(double x, double y) {
    // set position to (x, y), angle to 0.0 degrees, and pen color to black
    // make sure (x, y) is inside the square with corners (0, 0) and (1, 1)
  }
  
  public Turtle(double x, double y, double a) {
    // set position to (x, y), angle to a degrees, and pen color to black
    // make sure (x, y) is inside the square with corners (0, 0) and (1, 1)
  }
  
  public Turtle(double x, double y, double a, Color c) {
    // set position to (x, y), angle to a degrees, and pen color to c
    // make sure (x, y) is inside the square with corners (0, 0) and (1, 1)
  }
  
  public void move(double d) {
    // move forward by a distance d
    // make sure (x, y) is inside the square with corners (0, 0) and (1, 1)
    // use StdDraw.line(x, y, newx, newy) to draw the line
  }
  
  public void turnLeft() {
    // turn left 90 degrees; nothing needs to be drawn
  }
  
  public void turnRight() {
    // turn right 90 degrees; nothing needs to be drawn
  }
  
  public void turn(double a) {
    // turn by a degrees; nothing needs to be drawn
  }
  
  public void setPenColor(Color c) {
    // change the pen color to c
    // use StdDraw.setPenColor to actually change the pen color of the drawing
  }
  
  public static void main(String[] args) {
    // turtle that performs a random walk
    StdDraw.setCanvasSize();
    Turtle t = new Turtle();
    final double step = 0.005;
    for (int i = 0; i < 10000; i++) {
      t.turn(Math.random() * 360.0);
      t.move(step);
    }
  }
}

Lengthy/Creative Problems

1. An obvious use of Dictionary is for spell checking a document. Add a method named spellCheck that accepts a word as a string and returns a collection of suggested corrections for the word; the collection should be empty if the word is in the dictionary. You will need to do some research to find out how to measure the similarity between two strings; consider starting your research here.

 

2. An obvious use of Deck is to implement card games. Implement your favorite simple card game using Deck. You will probably find it useful to create other classes such as players for multiplayer games.