Showing posts with label CS A. Show all posts
Showing posts with label CS A. Show all posts

Wednesday, June 16, 2004

Exercise[35]

Insertion Sort (w/ Shuffle)

Pre-work

  1. In Barron's AP Computer Science A, read about Insertion Sort on p. 325.
  2. Optional: Read about insertion sort in another text book that will be made available to you in class.
  3. Explore https://www.tutorialspoint.com/compile_java_online.php.
  4. Study this Java implementation of insertion sort.
  5. Read the multiple choice questions on sorting and searching on pp. 331-345 of Barron's AP Computer Science A. Attempt to answer the questions that are related to insertion sort and then check your answer(s) using the answers provided on pp. 346-350.

Questions

  1. [1 point] Which questions in Barron's AP Computer Science A (pp. 331-345) involve or are related to insertion sort? List the question numbers only.
  2. [2 points] What determines whether this Java implementation of insertion sort sorts elements in ascending or descending order?

Create Activity

  1. [3 points] Create a multiple choice question about insertion sort. You question should include five choices (a - e) for the answer and only one correct answer. Your question may be inspired by a question from Barron's AP Computer Science A but must be substantially different, i.e. you should feel confident that no one would ever accuse you of plagiarizing the question.
  2. [15 points] Study DoTheShuffle. In the body of the email that you submit to the graders or in a single attached file, submit a single Java program that satisfies the following requirements:
    • [5 points] Place all of the classes need to compile and run DoTheShuffle in a single file and verify that the code compiles and runs. If code that you submit compiles, runs, and produces output, then you will earn the points for this portion of the activity.
    • [5 points] Modify the implementation of DoTheShuffle so that it outputs the original sequence, the sequence sorted in ascending order, the sequence sorted in descending order, and the sequence after shuffling. The output of the modified program should contain one more line of output than the original version of the program.
    • [5 points] Modify the implementation of the maneuver method of LazyStudentShuffler so that it actually shuffles the values of the array argument called seq. Make sure that your program runs as expected for input sequences comprised of zero elements (1 point), one element (1 point), two elements (1 point), and more than two elements (2 points).

Exercise[34]

Binary Search

Pre-work

  1. In Barron's AP Computer Science A, read about Binary Search on p. 329-330.
  2. Optional: Read about binary search in another text book that will be made available to you in class.
  3. Study and execute these Java implementations of binary search.
  4. Read the multiple choice questions on sorting and searching on pp. 331-345 of Barron's AP Computer Science A. Attempt to answer the questions that are related to binary search and then check your answer(s) using the answers provided on pp. 346-350.

Questions

  1. [1 point] Which questions in Barron's AP Computer Science A (pp. 331-345) involve or are related to binary search? List the question numbers only.
  2. [1 points] What is the difference between the Java implementations of binary search that implement Search<T> and the ones that implement MeteredSearch<T>?
  3. [2 points] Compare and contrast RecursiveBinarySearch and RepetitiveBinarySearch.

Create Activity

  1. [3 points] Create a multiple choice question about binary search. You question should include five choices (a - e) for the answer and only one correct answer. Your question may be inspired by a question from Barron's AP Computer Science A but must be substantially different, i.e. you should feel confident that no one would ever accuse you of plagiarizing the question.
  2. [6 points] Create two implementations of RecursiveBinaryMeteredSearch or RepetitiveBinaryMeteredSearch that are different from the ones provided. (Consider replacing the switch statement with if-else statements or calculating the value of middle differently.) Both implementations must compile and must implement MeteredSearch<T>. One implementation should be correct (to the best of your knowledge) and the other implementation should be flawed.
  3. [3 points] Indicate which of the two implementations of binary search that you are submitting is flawed and describe the flaw.

Exercise[33]

Sequential Search

Pre-work

  1. In Barron's AP Computer Science A, read about Sequential Search on p. 329.
  2. Read about sequential search in one or more of the following books, which will be made available to you in class:
    • Volume 3 (first edition) of The Art of Computer Programming (by D. E. K.), pp. 393-402.
    • Volume 3 (second edition) of The Art of Computer Programming (by D. E. K.), pp. 396-405.
    • Programming Classics (by Ian Oliver), pp. 196-198 and p. 200.
  3. Implement sequential search in Java with and without the use of a sentinel value.
  4. Read the multiple choice questions on sorting and searching on pp. 331-345 of Barron's AP Computer Science A. Attempt to answer the questions that are related to sequential search and then check your answer(s) using the answers provided on pp. 346-350.

Questions

  1. [1 point] Which questions in Barron's AP Computer Science A (pp. 331-345) involve or are related to sequential search? List the question numbers only.
  2. [2 points] List two topics related to sequential search that are discussed by Donald E. Knuth (in The Art of Computer Programming) or Ian Oliver (in Programming Classics) that are not discussed in Barron's AP Computer Science A.
  3. [2 points] What is a sentinel value and how can one be used in a sequential search algorithm?

Create Activity

  1. [3 points] Create a multiple choice question about sequential search. You question should include five choices (a - e) for the answer and only one correct answer. Your question may be inspired by a question from Barron's AP Computer Science A but must be substantially different, i.e. you should feel confident that no one would ever accuse you of plagiarizing the question.
  2. [3 points] Create another multiple choice question about sequential search. You question should include five choices (a - e) for the answer and only one correct answer. Your question must be related to a topic not discussed on p. 329 of Barron's AP Computer Science A.
  3. [3 points] Create an answer key for your two questions. For each question, the answer key should explain why the correct answer is correct and why the incorrect answers are incorrect.

Exercise[32]

Pre-work

  1. Read the lecture notes published at the following URL. Pay close attention to the Fibonacci example and the section on memoization.
    http://courses.csail.mit.edu/6.01/spring07/lectures/lecture4.pdf
  2. See also:
  3. Examine the code, read the comments, and follow the links posted at:
  4. Several reports, each listing a series of input values, output values, operation counts and run times for various "Fib functions" will be distributed in class. Study the data. Look for interesting patterns and surprising results.
  5. Become more familiar with the algorithms and their implementations by performing your own experiments using both the Java code (Funky Fibs and Big Fibs) and the JavaScript code (Funky Fibs).

    You can run the Java code as follows:

    1. Paste the code into the online editor at https://www.compilejava.net/. (Be sure to overwrite the code that appears in the editor by default.)
    2. Enter one or more command line arguments in the input field that appears immediately below the text editor and above the buttons.
    3. Press the COMPILE & EXECUTE button.

Assignment

  1. What is the common problem that all of the "Fib functions" (Java and JavaScript versions) are designed to solve?
  2. How many distinct algorithms are used to solve the problem?
  3. In English, describe how each algorithm works.
  4. Compare Funky Fibs (Java) with Big Fibs (Java). What is the main difference between the two implementations?
  5. Compare and contrast each distinct algorithm. In your analysis, answer the following questions.
    1. How easy or difficult do you think it is to understand the algorithm, implement it in code, and verify that it has been implemented correctly?
    2. How does the number of mathematical operations the algorithm performs vary as a function of the size of the inputs as well as the sequencing of successive inputs?
    3. How much space is required to store data used by the algorithm? Is the amount of space needed significant?
  6. Compare and contrast the implementations of the algorithms. In your analysis, answer the following questions.
    1. When does the implementation produce correct and incorrect results?
    2. Discuss the performance (the time it takes to produce an answer) of each implementation. Are the performance differences significant?
  7. What's the connection between each of following names and its corresponding "Fib function"?
    • Amnesic
    • Eidetic
    • Grinder
    • Unitary
    • Lacunar

Exercise[31]

Play Rock-Paper-Scissors

You are player 1. I am player 2.

A Rock-Paper-Scissors Tournament

The code displayed when you press the first four buttons below implements a rock-paper-scissors tournament. When viewing the JavaScript version of the code, a fifth button labeled Try to win by: followed by a value (3 by default) is visible.

Assignment

Question and Coding (100 points + possible bonus points)

  1. Describe the range of values that Math.random may return. (10 points)
  2. Modify Utility.randomInt (under To Do) so that it returns a random integer between the values of min and max inclusive. (20 points)
  3. Modify KingOfTheHill (under To Do) so that an instance of KingOfTheHill:
    • always wins at least one out of three matches in the Rock-Paper-Scissors tournament described above. (30 points)
    • always wins at least two out of three matches in the Rock-Paper-Scissors tournament. (15 points)
    • always wins at least two out of three matches in the fewest number of rounds. (pride)
  4. Submit your answer and your code for Utility.randomInt and KingOfTheHill by end of day, Tuesday, 3 January 2017 (extended due to snow days):
    • Email your answer and code to jspurgeon@vcstudent.org with the subject "Exercise[31]". (10 points)
    • Work submitted after the due date will be penalized 5 points per day late, up to 20 points.

How to Play in Java

@ www.compilejava.net ...

class PlayRPS {
  public static void main(String[] args) {
    RPSMatch match = new RPSMatch(null, null);
    match.setChoiceOfPlayer1(args[0]);
    match.setIndexOfChoiceOfPlayer2(Utility.randomInt(0, 2));
    System.out.println(match.getReplay());
  }
}

How We Play (Above)

function PlayRPS(choice) {
  var match = new RPSMatch(null, null);
  match.setChoiceOfPlayer1(choice);
  match.setIndexOfChoiceOfPlayer2(Utility.randomInt(0, 2));
  var results = match.getReplay();
  console.log(results);
  if (document.getElementById('RPSAlertFlag').selectedIndex === 0) {
    alert(results);
  }
}

Exercise[30]

Finish implementing the Java or JavaScript Util methods shown below (i.e. toArray, copyOfArray, swap, flip, flipCopyOfArray, and flipCopyOfString).

When you are finished, send an email to jspurgeon@vcstudent.org with the subject "Exercise[30]". Include your completed functions in the body of the email message or include a reference to the code in the message.

Grading Rubric

  • Each correctly completed method is worth 10 points.
  • Following the instructions above is worth 10 points.
  • Work turned in late will be penalized 10 points.

Due Date

End of day Mon, 5 Dec 2016

Note

java FlippantFunctions "abc" should output:
abc
cba
abc
cba

FlippantFunctions.main(["abc"]) should output:

abc
cba
["a", "b", "c"]
["c", "b", "a"]

Exercise[29]

Give not that which is holy unto the dogs, neither cast ye your pearls before swine, lest they trample them under their feet, and turn again and rend you.
Matthew 7:6
King James Bible

The study of algorithms offers much to the practicing programmer. A course on the subject equips students with algorithms for important tasks and design techniques for attacking new problems. We'll see in later columns how advanced algorithmic tools sometimes have a substantial impact on software systems, both in reduced development time and faster execution speed.

As crucial as those sophisticated ideas are, algorithms have a more important impact at a more common level of programming. In his book Aha! Insight (from which I shamelessly stole my title), Martin Gardner describes the contribution I have in mind: "A problem that seems difficult may have a simple, unexpected solution." Unlike the advanced methods, the aha! insights of algorithms don't come only after extensive study; they're available to any programmer willing to think seriously before, during and after coding.

Jon Bently
“Column 2: Aha! Algorithms”, p. 11
Programming Pearls, 1986

Professor Strunk was a positive man. His book contained rules of grammar phrased as direct orders. In the main I have not attempted to soften his commands, or modify his pronouncements, or delete the special objects of his scorn.
E. B. White
“A Note on This Book”, p. v
The Elements of Style, 1959

It turns out that style matters in programming for the same reason that it matters in writing. It makes for better reading.
Douglas Crockford
“Chapter 9 - Style”, p. 94
JavaScript: The Good Parts, 2008

Functional composition is better.
Email message from Douglas Crockford
Sent to John Spurgeon on Sun, Oct 23, 2016 at 7:53 PM

Tom Finnegan's Big Problem

Tom Finnegan has a homework assignment that is due soon. He's been procrastinating and hasn't been paying attention in class, so he copied some clever code that Tamsin Finnegan wrote. Tom thought he was being clever until Tamsin informed him, at the eleventh hour, that the code he copied wasn't code for Tom's assignment at all. It was just something she did for fun! (Tamsin was wise to Tom all along and is hanging him out to dry.) Tom's actual assignment is to implement a Utility method called josephusNumber, which must be defined in terms of two parameters: rebelCount and skipCount. The method must return the Josephus number corresponding to the argument values passed to the method as demonstrated here. (Note that skipCount may be zero or negative!) Tom's teacher gave him some "Flippant Functions" to work with. All he has to do is find the right function and modify it.

Your Assignment

Using Tom's Flippant Functions, help Tom get out of his jam.

The function Tom needs to find is named cycleShiftLeft and is defined in terms of three parameters: n, i and j. After you've found the function, make sure you understand its purpose and how it works. Then figure out what needs to change. Make the necessary changes and test them. After you have tested your function using the Test Fixture below:

  1. Copy your modified code directly from the Test Fixture below and paste it into the body of an email message.
  2. If you want to receive the bonus points, include your answer to the bonus question in the body of the email message.
  3. Make sure the message is addressed to: jspurgeon@vcstudent.org
  4. Make sure the subject of the message is: Exercise[29]
  5. Send the email.

Grading Rubric

  • Not counting bonus points, this assignment is worth 100 points.
  • If your submission is late or if you submit a corrected assignment after the due date, you will lose 10 points.
  • If your code does not produce the correct results, you will lose up to 50 points.
  • If the style of the code that you submit is not consistent with the style of the code provided, you may lose up to 10 points.
  • If your code is not submitted in the body of an email message as instructed above, you will lose 10 points.
  • If your code is not sent to the correct email address, you will lose 10 points.
  • If the subject of your email message is not "Exercise[29]", you will lose 10 points.
  • If you answer the bonus question (below) correctly, you will receive up to 10 bonus points.

Test Fixture

Bonus Question (worth 10 points)

What's the connection between this exercise and the parable of the laborers? (Matthew 20:1-16)

Due Date

EXTENDED: This assignment is due by end of day Tuesday, 29 Nov 2016.

Exercise[28]

Why?

This exercise has several important objectives:

  • It provides practice reading a small piece of powerful code that makes use of several logical and bitwise operators common to Java and JavaScript.
  • It demonstrates and provides exposure to a simple while loop.
  • It introduces a technique for and provides practice with the act of mentally stepping through code and keeping track of values of variables as they change in order to comprehend the code.
  • It introduces the curious and surprising useful technique of shifting and cycling bits.

JavaScript Code

The following JavaScript function performs a one bit cycle shift left of a number n:

function cycleShiftLeft(n) {
  var oneBitCycleShiftLeft; // result
  var MAX_MASK = 1 << 30; // constant limitation
  var nShiftedLeft = n << 1;
  var bitMask = 1;
  while (bitMask <= n && bitMask <= MAX_MASK) {
    bitMask = bitMask << 1;
  }
  oneBitCycleShiftLeft = (bitMask ^ nShiftedLeft) + 1;
  return oneBitCycleShiftLeft;
}

Tabular Code Trace

The following table traces the execution of the function above when n equals 2. Each row in the table shows the values of the function's variables as of a particular step in the execution of the function, where a step corresponds to the evaluation of a line of code terminated by a semicolon. (Note that the values of all variables are the same in steps 6 and 7, because step 7 corresponds to the return statement at the end of the function.)

cycleShiftLeft(2):

Stepn (binary)oneBitCycleShiftLeftMAX_MASK (binary)nShiftedLeft (binary)bitMask (binary)
010uninitializedundefinedundefinedundefined
110uninitialized1 << 30undefinedundefined
210uninitialized1 << 30100undefined
310uninitialized1 << 301001
410uninitialized1 << 3010010
510uninitialized1 << 30100100
61011 << 30100100
71011 << 30100100

Now you try!

Produce a table like the one above showing the execution of the function when n equals 6. Your table may be hand-written or produced electronically. Either way, the table should trace the function exactly the same way the table above does. Your table should have the same columns and column headings, and it should use exactly the same step-numbering system, English terminology, and bases for representing numbers. If you produce the table on paper by hand, you must submit a clear image of your work as an attachment to an email message.

Hints (added on Wed, 16 Nov 2016)

Hint #1:

Here's an easy and efficient way to approach this assignment: Using a mouse, select the table above. (Be sure to select the entire table. To make sure you've selected the entire table, also select some text before and after the table.) Copy the selected contents. Paste the copied contents into an Excel spreadsheet. For example:

Remove any extraneous text that you pasted. Adjust the widths of the columns. Add rows and modify the contents of cells as needed. Voila!

You have to do the work of reading the code, understanding what it does, and recalling how logical and bitwise operators work, of course. But the mechanics of producing the table can be that easy!

Hint #2:

Still struggling with the concepts?

Explore the fascinating world of one bit cycle shift left >> HERE <<

Grading Rubric

  • 15 points will be awarded for emailing your table in the body of an email message, as an attachment to an email message, or as a URL directly referencing your work published on a blog to jspurgeon@vcstudent.org with the string "Exercise[28]" in the subject of the email message on or before the due date.
    • If your work is submitted late, then you will lose 5 points.
    • If your email message does not contain the string "Exercise[28]" in exactly that format or if it contains anything else in the subject line of your email message, then you will lose 5 points.
    • If you send me a URL that does not directly reference a blog post containing your table, or if you send a reference to work stored anywhere other than on a blog, then you will lose 5 points.
  • Two points will be awarded for each and every cell in the table that contains the correct value. For example, the table above has 6 columns and 9 rows, yielding 54 cells or 108 points; your table must have the same number of columns and more rows, so it will be worth more points. English words may be in upper, lower or camel case. Numbers must be represented exactly as shown in the example above.
  • Up to 15 bonus points will be awarded if a) you post your answer on a blog using HTML table tags, and b) your table looks essentially identical in structure to the one above. (You must use table heading tags for the first row of headings and table data tags for the data rows to receive all of the potential bonus points.)
  • The score you receive for this exercise may be weighted to reflect its significance relative to other scores that contributed to your grade for the quarter.

Due Date

For full credit, your work must be received via email (as specified above) by end of day, Friday, November 18, 2016.

Exercise[27]

The following coding project is designed to provide practice with many of the important topics covered in class to date. It provides opportunities to practice reading and comprehending code and requirements as well as designing, implementing, using and testing software. If the project seems too easy, then expand the scope of the assignment (while continuing to satisfy all the requirements) by developing software to accommodate other types of shapes, such as kites, triangles, n-sided polygons, etc.

Coding Project


Design and implement code (in Java or JavaScript) that enables you to create instances of objects of type: Your code should meet the following requirements:
  • All objects should have a method called side defined in terms of a parameter called n; the method should return a floating point number representing the length of the side corresponding to the argument value passed to the method.
  • All objects should have a method called angle defined in terms of parameter called n; the method should return a floating point number representing the number of degrees of the angle corresponding to the argument value passed to the method.
  • All objects should have a method called perimeter that returns the length of the perimeter of the shape represented by the object.
  • All objects should have a method called area that returns the area of the shape represented by the object.
  • The class (Java) or constructor function (JavaScript) used to produce Quadrilateral objects should have the following static methods defined in terms of a parameter called q. Each method should return true or false; a method should return true if and only if the value of the parameter q is an object representing a valid instance of the shape connoted by the name of the method. The method names should be:
    • isParallelogram
    • isRhomboid
    • isRhombus
    • isRectangle
    • isSquare
  • Constructors should be defined in terms of parameters as follows.
    • Quadrilateral: s0, s1, s2, a1, a2
    • Parallelogram: s02, s13, a13
    • Rhomboid: s02, s13, a13
    • Rhombus: s0123, a13
    • Rectangle: s02, s13
    • Square: s0123
  • The parameter names listed above should correspond to the side and interior angle labels shown in the following image of a quadrilateral. For example, the value of the parameter s02 (above) is the length of sides s0 and s2 (below), and the parameter a1 (above) is the measure in degrees of angle a1 (below).
You are strongly encouraged to:
  • Use the Polygon JavaScript constructor function or Java class shown here.
  • Consider and verify the following statements:
    • A parallelogram is a quadrilateral.
    • A rhomboid is a parallelogram. (A rhomboid is not a rhombus.)
    • A rhombus is a parallelogram. (A rhombus is not a rhomboid.)
    • A rectangle is a parallelogram. (A rectangle may be a rhombus but cannot be a rhomboid.)
    • A square is a rectangle.

Recommended Reading


Composition vs. Inheritance: How to choose?

AP Computer Science Principles - JavaScript
  • JavaScript: The Definitive Guide, 6th Edition by David Flanagan
    • Chapter 7 Arrays (pp. 141-161)
AP Computer Science A - Java
  • Barron's AP Computer Science A, 7th Edition by Roselyn Teukolsky
    • Chapter 6 Arrays and Array Lists (pp. 233-256)

Exercise[26]

Practice reading, understanding and modifying code...

Exercise[25]

When working with non-trivial amounts of code, it's common to partition the code and save the pieces in separate files. Code and the files that contain the code need to be carefully organized. And files need to be somehow related to each other when there are dependencies between pieces of code they contain. This exercise provides practice taking existing code not yet stored in files, placing it in files, and verifying that the code can then be used as intended. The exercise also sets up exploration of programming topics related to the stopwatch code.

Make a One-Button Stopwatch


Notice how the JavaScript and Java code shown in One-Button Stopwatch is partitioned. Using a text editor, place the code snippets into separate files. Name the files and place the files in particular directories as suggested by the headers above each section of code and as described below.

If you're working with the JavaScript code, all of the files should be placed in a single directory and should have the same name as the header above the section of code. Load the Stopwatch.html file using a web browser.

If you're working with the Java code, then the file named Stopwatch.java should be placed in a directory that contains a directory named com; the com directory should contain a directory named blogspot; and the blogspot directory should contain a directory named finnegantakes. The other .java files should be placed in the finnegantakes directory. Compile all of the .java files and interpret the Stopwatch class.

Recommended Reading


AP Computer Science Principles - JavaScript
AP Computer Science A - Java

Exercise[24]

Read about and study the behavior of a traditional stopwatch. (Also read about has-a relationships!)

Then:
  1. Provide the missing JavaScript or Java code needed to complete this partial implementation of a traditional stopwatch.
  2. Use your implementation of a stopwatch to study how long it takes a JavaScript or Java for loop to increment a counter one billion times. What did you learn?
  3. List all of the distinct and worthwhile "sequences of events" that you should test to ensure that your implementation of a traditional stopwatch works correctly. For example:
    • Sequence of events: New stopwatch!, press Top. Expected result: displays 0.
    • Sequence of events: New stopwatch!, press Top, press Top. Expected result: displays a whole number greater than zero.
    • etc.

Exercise[23]

An algorithm for success

  1. Go to a Math Class:
  2. View the quiz and read the code.
  3. Take the quiz.
  4. Run the code.
  5. Grade yourself.
  6. If you are happy, then hide the quiz and relax; otherwise, get help if needed and then go to step 1.
FAIR WARNING: If you come to either of my classes tomorrow, my magic eight ball predicts it is certain that you will repeat steps 1 and 2, and without a doubt the quiz will be very similar but not identical!

Exercise[22]

First, spend a few minutes reading and/or listening to the story As Buyers Circle, Could Twitter Be Better Off As A Nonprofit? by Laura Sydell (dated October 5, 201612:34 PM ET).

Then invest at least 30 additional minutes educating yourself:
Then, over the course of a week, invest a few hours as follows:

Write something about something you learned. Cite one or more sources. Cite at least one source that is less than a year old. Publish what you wrote on a blog or email what you wrote to someone else other than your computer science teacher. Ask for feedback. Listen to the feedback you receive. Then revise what you wrote based on the feedback you received. Send what you wrote or a reference to what you wrote to your computer science teacher.

Then let it go and move on until you feel the urge to return to what you wrote, if ever.

Exercise[21]

  1. Listen to yourselves.
  2. Listen to these words.
  3. Literally listen...

Exercise[20]

Ready... Set...
  1. First, read (and comprehend!) Timer (JavaScript) or Timer (Java).
  2. Second, read the JavaScript version or Java version of You complete me - stop.
  3. Third, figure out what code you can provide that would complete the pause function/method.
  4. Finally, produce and test a JavaScript or Java program that includes an instance of a Timer object and your implementation of pause. (Hint: the partially complete version of pause already includes an instance of a Timer object, more or less.) Make sure your program uses pause to produce some observable effect.