CS46A Lab

Fundamental Types

Copyright © Cay S. Horstmann, Kathleen O’Brien 2009-2014 Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

See lab2 for reporting instructions.

  1. Random Walk
    1. Dust particles move across a plane by a fixed distance, then change direction by turning at a random angle between 0 and 360 degrees, then move again by the same distance, and so on. Intuitively, it would seem that the particles never move very far because all those motions would cancel each other out. This turns out not to be true—it can be shown that the particles travel arbitrary distances, given enough time. Would this random move strategy work for a vacuum cleaner? Let's use our graphics library to explore.

      Make a new project lab5b and import the graphics library. Make a class RandomWalk and declare the public static void main(String[] args) method within it. In the main method, create a variable vacuum of type Picture. Create a new Picture object with the file "large_roomba.png" Move it to position (200, 200) and draw it. Driver: What is the code of your main method?

      This image should have been included in your project when you imported the graphics package. If not, here it is. Right click and download to the project folder

      roomba

      Here we just use a picture instead of a Robot object because our robots can only make 90 degree turns.
    2. First, we need to get a random angle. The call Math.random() yields a random number between 0 and 1. But we need a random number between 0 and 360, so multiply by 360.
    3. But in Java, angles are measured in radians, so you need to convert to radians. There is a Math method for that too. Scribe: What is it?
    4. Now put that all together. Scribe: What is the Java statement to make a random angle in radians?
    5. Once you have an angle, we get the x- and y-distance like this

      double dx = distance * Math.cos(angle);
      double dy = distance * Math.sin(angle);

      Here distance is a variable that gives the distance the vacuum moves in one step. For now, set it to 50.

      Add instructions to your program that compute angle, dx, and dy. Then move the picture by dx and dy. Run your program. Scribe: What happens?

    6. Run the program again. Scribe: What happens? Scribe: How can you tell that something random is happening?
    7. Now we want to repeat this many times. Put the computations of angle, dx, and dy, and the call to translate inside the loop below. Do not worry about the mechanics of the for loop. We haven't covered that yet. Just know that it will execute the code inside the braces 20 times. Your job is to complete the statements, which you already did in steps 2 through 5.

      Picture vacuum = new Picture("large_roomba.png");
      vacuum.translate(200, 200);
      vacuum.draw();              
      for (int i = 1; i <= 20; i++)
      {
         double angle = ...;
         double dx = ...;
         double dy = ...;
         vacuum.translate(..., ...);     
      }

      We'll discuss the loop in chapter 6—the code means “run the statements inside 20 times”. Just copy/paste it.

      Scribe: What happens when you run the program?

    8. It's difficult to see where the vacuum cleaner went. After each call to translate, construct a circle with coordinates vacuum.getX() and vacuum.getY() and diameter 10. Fill the circle. Scribe: What happens when you run the program now?
    9. Adjust the distance to 5 and run the loop 3000 times. Scribe: What happens?
    10. When you look carefully at the output, you'll notice that the circles trace the top left corner of the picture, not the center. It looks prettier when they trace the center. Go ahead and make that adjustment. You probably want to make a sketch. What is the center of the vacuum? (It depends on vacuum.getWidth() and vacuum.getHeight(). You want the same center for the circle, but you need to specify its top left corner, so how do you get there? (It depends on the circle's diameter.) You can look back at lab 4 to see how to draw a circle.
    11. Driver: When you got this done, copy the code in your report.
  2. Manipulating Strings

    The Exploratorium has a nifty exhibit showing that, according to research at Cambrigde Uinversity, our brain tolerates scrambled letters in a word when reading text.

    The following exercises explore this scrambling.

    1. Create a new project in your lab5 folder. Call it whatever you like. Copy this class into the project: StringScrambler . Modify the scramble method. The method should return a word that is made up of
      • the last letter of word
      • all but the first and last letters of word
      • the first letter of word

      For example, if the input is received, the output should be

      deceiver

      Hint: Call substring method three times (Once to get the last letter. Once to get all the characters except first and last letters of word. Once to get the first letter) and then concatenate (+) the results.
      Driver: What is your scramble method?

    2. Now you need to test your program by making an object of type StringScrambler in the BlueJ workbench. It is a good idea to test with data where you know the answer. Call the scramble method with the word "received".

      Scribe: Did you get the answer you expected?

    3. Now call the scramble method with an input of resigned. Scribe: What output do you get?
    4. What happens when you use very short strings, i.e. strings with 2 characters? 1 character? The empty string? Scribe: Explain your results.
    5. Use an if statement to fix the problem. Driver: what is the code for the method now?
    6. In the Bluej workbench, call the scrambleSentence method with a sentence of your choice such as "Java: easy and enjoyable". Just run it—it calls your scramble method for each word in the sentence.

      Driver: What result do you get?

    7. Actually, this scrambling isn't so good. For best results, you should leave the first and last letter alone. Let's change the scramble method so that it scrambles the second and third letter of each word. For example, "word" should get changed to "wrod".

      Driver: What is your scramble method now?

    8. Now test the updated method. Call scrambleSentence again with the same sentence as in step 4. Driver: What is the result?
    9. That is better. But we would like to switch any letter with its successor, as long as we leave the first and last character alone. Instead of swapping positions 1 and 2, let's swap positions index and index + 1 where index is a random number between 1 (the second character) and the second to the last character. For example, if the string has 10 letters, we need to calculate the maximum value for the index to swap. The index of the last character is 9, the one before that is 8, We do not want to swap 8 and 9 (9 is the last character) so 7 is the last character we want to swap. We would need a random number between 1 and 8.

      Scribe: What is the code to get the index of the next to the last character of a string?

    10. Now you need to get a random number. A randomInt method has been provided for you. It returns a random number greater than or equal to the first argument and less than the second argument. To get a random number to use as the index to swap, use: index = randomInt(1, ...). You need to decide what the second argument should be. (See the last strp)

      Driver: What is your scramble method now?

    11. Try scrambleSentence again with the same sentence as in step 4.

      Scribe: What is the result?

    12. Now we want our method to swap any two characters as long as we leave the first and last alone. Pick a random location, but not the first letter or the last two letters. You will call randomInt with this statement index = randomInt(num1, num2). You need to figure out what num1 and num2 need to be.

      Scribe: What code should you use to find index?

    13. Now you need another random location. It needs to be after the first random location(index) that you picked in the previous step but not the last letter of the string. Swap those. You will have to use substring several times. Start by getting the beginning of the phrase - the substring up to but not including the character at index1. Get the substring of the character at index2. Concatenate it on to the beginning portion. See if you can figure out the rest.

      Make sure all the letters from the original are in the scrambled string.

      Driver: What is your scramble method now?

    14. Try scrambleSentence again with the same sentence as in step 5. Driver: What is the result?
  3. Distances
    1. When you are given two points (x1, y1) and (x2, y2) on the plane, the distance between them can be computed according to the following figure:

      Write Java code that computes a variable double distance from variables x1 and x2. Use variables dx and dy.

      For those of you interested in efficiency: when the power is 2, it is actually more efficient to use dx * dx rather than math.pow(dx, 2). For any other power Math.pow is more efficient.

    2. In BlueJ, complete this class Distance with your expression and run it with test cases (x1, y1) = (0, 0) and (x2, y2) = (30, 40). What output do you get?
    3. Pick three more test cases: A horizontal line, a vertical line, and a line with a 45 degree angle. What outputs do you get? Why are they correct?
    4. Driver: What is your code?
  4. Interactive Review and Practice

    Do the Interactive Review and Practice of Chapter 5 individually. You can discuss with your partner and ask the lab instructor for help.

    Make sure to receive 100% for each problem. Click Reset or refresh the page if you have made mistakes.