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 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.
[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.
[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).
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 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.
[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.
[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 points] Indicate which of the two implementations of binary search that you are submitting is flawed and describe the flaw.
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 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 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.
[2 points] What is a sentinel value and how can one be used in a sequential search algorithm?
Create Activity
[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.
[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 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.
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.
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:
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.)
Enter one or more command line arguments in the input field that appears immediately below the text editor and above the buttons.
Press the COMPILE & EXECUTE button.
Assignment
What is the common problem that all of the "Fib functions" (Java and JavaScript versions) are designed to solve?
How many distinct algorithms are used to solve the problem?
In English, describe how each algorithm works.
Compare Funky Fibs (Java) with Big Fibs (Java). What is the main difference between the two implementations?
Compare and contrast each distinct algorithm. In your analysis, answer the following questions.
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?
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?
How much space is required to store data used by the algorithm? Is the amount of space needed significant?
Compare and contrast the implementations of the algorithms. In your analysis, answer the following questions.
When does the implementation produce correct and incorrect results?
Discuss the performance (the time it takes to produce an answer) of each implementation. Are the performance differences significant?
What's the connection between each of following names and its corresponding "Fib function"?
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)
Describe the range of values that Math.random may return. (10 points)
Modify Utility.randomInt (under To Do) so that it returns a random integer between the values of min and max inclusive. (20 points)
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)
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.
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);
}
}
class RPSMatch{
static class CONST {
final static int PLAYERS_TIE = 0;
final static int PLAYER1_WINS = 1;
final static int PLAYER2_WINS = -1;
static String[] CHOICES() {
String[] a = {"rock", "paper", "scissors"};
return a;
}
}
static int getIndexOf(String choice) {
String[] choices = CONST.CHOICES();
for (int i=0; i< choices.length; i++) {
if (choices[i].equals(choice)) {
return i;
}
}
return -1;
}
static String getChoiceAt(int index) {
return index >= 0 && index <= 2 ?
CONST.CHOICES()[index] : "bad choice";
}
RPSCompetitor player1 = null;
RPSCompetitor player2 = null;
class State {
int indexOfChoiceOfPlayer1;
int indexOfChoiceOfPlayer2;
double netScore;
long roundsPlayed;
}
State state;
RPSMatch(RPSCompetitor p1, RPSCompetitor p2) {
player1 = p1;
player2 = p2;
state = new State();
}
int getIndexOfNextChoiceOf(RPSCompetitor player) {
if (player == null) {
throw new Error("player is null");
}
if (player instanceof CanGetIndex) {
return player.getIndex();
}
if (player instanceof CanGetChoice) {
return RPSMatch.getIndexOf(player.getChoice());
}
throw new Error("player can't play");
}
void setPlayer1(RPSCompetitor player) {
player1 = player;
}
void setPlayer2(RPSCompetitor player) {
player2 = player;
}
void setChoiceOfPlayer1(String choice) {
setIndexOfChoiceOfPlayer1(RPSMatch.getIndexOf(choice));
}
void setChoiceOfPlayer2(String choice) {
setIndexOfChoiceOfPlayer2(RPSMatch.getIndexOf(choice));
}
void setIndexOfChoiceOfPlayer1(int i) {
if (-1 < i && i < 3) {
state.indexOfChoiceOfPlayer1 = i;
}
}
void setIndexOfChoiceOfPlayer2(int i) {
if (-1 < i && i < 3) {
state.indexOfChoiceOfPlayer2 = i;
}
}
int getIndexOfChoiceOfPlayer1() {
return state.indexOfChoiceOfPlayer1;
}
int getIndexOfChoiceOfPlayer2() {
return state.indexOfChoiceOfPlayer2;
}
double getNetScore() {
return state.netScore;
}
long getRoundsPlayed() {
return state.roundsPlayed;
}
void makePlayersChoose() {
int i1 = getIndexOfNextChoiceOf(player1);
int i2 = getIndexOfNextChoiceOf(player2);
setIndexOfChoiceOfPlayer1(i1);
setIndexOfChoiceOfPlayer2(i2);
}
void revealChoices() {
state.netScore += getOutcome();
state.roundsPlayed++;
}
void playAgain() {
makePlayersChoose();
revealChoices();
}
int getOutcome() {
int i1 = getIndexOfChoiceOfPlayer1();
int i2 = getIndexOfChoiceOfPlayer2();
int numChoices = CONST.CHOICES().length;
int beatsPlayer2 = (i2 + 1) % numChoices;
return (i1 == i2) ? CONST.PLAYERS_TIE :
(i1 == beatsPlayer2 || i2 == -1) ? CONST.PLAYER1_WINS :
CONST.PLAYER2_WINS;
}
String getChoiceOfPlayer1() {
return RPSMatch.getChoiceAt(getIndexOfChoiceOfPlayer1());
}
String getChoiceOfPlayer2() {
return RPSMatch.getChoiceAt(getIndexOfChoiceOfPlayer2());
}
String getResult() {
int outcome = getOutcome();
return outcome == CONST.PLAYER1_WINS ? "player 1 wins" :
outcome == CONST.PLAYER2_WINS ? "player 2 wins" : "players tie";
}
String getReplay() {
return getChoiceOfPlayer1() +
" vs. " + getChoiceOfPlayer2() +
": " + getResult();
}
double getPlayer1Score() {
return (getRoundsPlayed() + getNetScore())/2;
}
double getPlayer2Score() {
return (getRoundsPlayed() - getNetScore())/2;
}
String getScoreBoard() {
return "Player 1: " + getPlayer1Score() +
", Player 2: " + getPlayer2Score();
}
}
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"]
class Util {
public static char[] toArray(String s) {
int i = s.length();
char[] array = new char[i];
return array;
}
public static char[] copyOfArray(char[] array) {
int i = array.length;
char[] copy = new char[i];
return copy;
}
public static char[] swap(char[] array, int i, int j) {
return array;
}
public static char[] flip(char[] array) {
return array;
}
public static char[] flipCopyOfArray(char[] array) {
char[] copy = Util.copyOfArray(array);
return Util.flip(copy);
}
public static String flipCopyOfString(String s) {
String f = "";
return f;
}
}
class FlippantFunctions {
public static void main(String[] args) {
String s = args[0];
String sf = Util.flipCopyOfString(s);
char[] a = Util.toArray(s);
char[] af = Util.flipCopyOfArray(a);
System.out.println(s);
System.out.println(sf);
System.out.println(a);
System.out.println(af);
}
}
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 twoparameters: 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.
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:
Copy your modified code directly from the Test Fixture below and paste it into the body of an email message.
If you want to receive the bonus points, include your answer to the bonus question in the body of the email message.
Make sure the message is addressed to: jspurgeon@vcstudent.org
Make sure the subject of the message is: Exercise[29]
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
Always looking for a shortcut, Tom somehow obtained the following strange-looking program from his teacher, who noticed that Tom took it but doesn't mind. You may use it to gauge how well you and Tom are doing on the assignment. (Although he claims he doesn't know how it got there, Tom has Teacher.grade() written in ink on his left palm.)
The Whys and Wherefores
This assignment provides more practice in the art of following instructions carefully. If you follow the rules of the assignment, then you will receive the specified points; if not, you won't—just like when you're programming a computer, where you have to follow the rules of the programming language; otherwise, the program won't run as desired.
This assignment provides more practice reading, comprehending, and making small but important changes to a very modest amount of nontrivial code.
This assignment provides review of and practice with key concepts covered in class, including:
Arrays
Loops
Recursion
Program design
Algorithms
Cycle Shift Left
This assignment emphasizes the fact that Java and JavaScript programs can look very similar syntactically, even though the two languages are quite different. The code in this assignment shows that it is sometimes not difficult to understand and work with JavaScript code if you know how to program in Java but have not done much programming in JavaScript.
Grading Rubric
You must submit JavaScript code for the Student object shown above in the body of an email message sent to jspurgeon@vcstudent.org with only the string Exercise[29] in the subject of your email. The code you submit may not produce any errors when copied and pasted into the JavaScript command prompt of a web browser. You will receive 15 points if and only if the email message you send and the code it contains meets these requirements.
If the work you submit is late, you will lose 5 points.
If code submitted prior to the due date produces any errors (when pasted into the command prompt), you will lose 5 points, even if you submit code that does not produce errors after the due date.
If your email message is sent to the wrong address OR does not contain only the string Exercise[29] in the subject of the message OR does not contain code in the body of the email message, you will lose 5 points.
Your code must maintain the style of indentation (which uses spaces, not tab characters) and usage of curly braces shown in the code above. You will receive 15 points for meeting this requirement. Each instance of a tab character, improperly indented code, or an improperly formatted curly brace will be penalized 5 points up to a maximum penalty of 15 points.
You will receive 30 points if the code you submit produces the correct Josephus number for all tests where the value of skipCount is one. You will lose points (up to a maximum of 30 points) for each test that your code does not pass where the value of skipCount is one.
You will receive 40 points if the code you submit produces the correct Josephus number for all tests where the value of skipCount is greater than one. You will lose points (up to a maximum of 40 points) for each test that your code does not pass where the value of skipCount is greater than one.
At any time prior to the end of the quarter, the weighting of this assignment or any other graded assignment might be adjusted to reflect the significance of the assignment relative to other graded assignments.
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.
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.
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):
Step
n (binary)
oneBitCycleShiftLeft
MAX_MASK (binary)
nShiftedLeft (binary)
bitMask (binary)
0
10
uninitialized
undefined
undefined
undefined
1
10
uninitialized
1 << 30
undefined
undefined
2
10
uninitialized
1 << 30
100
undefined
3
10
uninitialized
1 << 30
100
1
4
10
uninitialized
1 << 30
100
10
5
10
uninitialized
1 << 30
100
100
6
10
1
1 << 30
100
100
7
10
1
1 << 30
100
100
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.
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:
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.)
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
JavaScript: The Definitive Guide, 6th Edition by David Flanagan
Provide the missing JavaScript or Java code needed to complete this partial implementation of a traditional stopwatch.
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?
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.
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!
Finally, pick one web technology listed on the Web technology For developers page that interests you and spend at least ten minutes exploring that technology in more depth.
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.
Third, figure out what code you can provide that would complete the pause function/method.
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.