Solutions for Exercises from Programming with JavaScript by Dionisio & Toal
Solutions for Exercises from Programming with JavaScript by Dionisio & Toal
1.
Answers vary. This exercise involves reading an article and writing a summary.
tb9
2.
A coding strand is a DNA strand that stores the base sequences for forming a protein. mRNA
synthesis is the process by which a coding strand is transcribed into messenger RNA (mRNA),
which is then used to guide the formation of proteins. These entities are related to the common
understanding of programming in that the coding strand serves as “storage” for program code
and mRNA synthesis is analogous to “loading” a copy of that code so that it may be “executed”
(i.e., used to form a particular protein).
8@
3.
The very broad subfields are Discrete Structures; Programming Fundamentals; Algorithms
and Complexity; Architecture and Organization; Operating Systems; Net-Centric Computing;
Programming Languages; Human-Computer Interaction; Graphics and Visual Computing;
Intelligent Systems; Information Management; Social and Professional Issues; Software
Engineering; and Computational Science and Numerical Methods. Among the more detailed
fields are Algorithms; Artificial Intelligence; Compilers and Interpreters; Computation Theory;
gm
Computer Architecture; Computational Complexity; Computational Geometry; Data Mining; Data
Structures; Databases; Decision Support Systems (Knowledge-Based Systems); Distributed,
Parallel, and Cluster Computing; Digital Libraries; Graphics; Human Computer Interaction;
Information Theory; Machine Learning; Modeling in Science, Engineering, and Finance;
Multiagent Systems; Multimedia; Natural Language Processing; Networks and Internets;
Neural and Evolutionary Computing; Numerical Analysis; Operating Systems; Programming
Languages; Real-time Systems; Robotics; Scientific (Numeric, Symbolic) Computation;
Search and Information Retrieval; Security (including Cryptography and Cryptanalysis);
ail
Software Engineering; Virtual Reality (and Virtual Worlds); Vision and Pattern Recognition; and
Visualization.
4.
Answers vary depending on the school the one choses to investigate.
.co
5.
Answers vary, but possibilities include Electronic Markets, Virtual Worlds, Computational
Biology, Biological Databases, The Sociopathology of Living Online, Language and Thought,
Computational Linguistics, Computers and Kinetics, Mechanical Theorem Proving, Open
Source Computing for Humanity, Computing and Privacy.
m
7.
Answers vary. This exercise involves conducting an interview.
8.
Answers vary, but here are some likely answers:
● JavaScript runs in almost every browser on the planet and has no significant
competitors in that space.
● Ruby became incredibly hip in the aughts due to a web framework called Rails.
● Io was created to explore the conceptual unification of dynamic languages.
● Lua forms much of the codebase for World of Warcraft.
● Self became a major influence on JavaScript.
● Java was going to be the language for applets running in web browsers, but instead
turned out to incredibly popular on the server side.
● Python uses indentation, not braces or begin-ends, to structure code.
● C is the most popular systems language in the world.
● ActionScript is the language behind the popular Adobe Flash product.
● Smalltalk was the language behind the first graphics workstations.
● LISP is considered by many to be the most beautiful of all languages.
● Ada was mandated for most U.S. Department of Defense contracts in the 1980s.
● bash is the default shell for most Linux-based operating systems.
● SQL is understood by nearly every relational database system on the planet.
● Go was created at Google.
9.
This exercise involves creating a spreadsheet.
10.
This exercise involves adding data to the spreadsheet constructed in Exercise 9.
11.
RSA is not provably secure because it can be broken by factoring numbers. If the numbers
are very large, factoring can take years or decades with currently technology; however, no one
knows whether or not better algorithms even exist to factor numbers much more quickly.
12.
This exercise consists of reading an article.
13.
Answers vary, but a sampling of headlines that show the breadth of computing include
● Robot Teaches English as Second Language
● Argon, the Augmented Reality Web Browser, Available Now on iPhone
● 'Fingerprints' Match Molecular Simulations With Reality
● DARPA Funds Hackers to Innovate Military Tech
● Light-Based Computing, Quick as a Thought
● ONR Encouraging Women to Pursue STEM Careers
● Researchers Use Wi-Fi Mesh Network to Monitor Melting Glaciers
● The Cyberweapon That Could Take Down the Internet
● Computer-Assisted Diagnosis Tools to Aid Pathologists
● Subversive Apps Help Citizens Fight State Silencing
● Gamers Succeed Where Scientists Fail
14.
The argument as to whether a brain is a type of computer depends on how one
defines "computer." If one defines a computer as any information processor making use of
sensory input that causes actions based on those inputs then brains fall into that category. This
is the argument "for" the proposition. In fact this definition of computer includes entire networks
of computers, which act in a highly distributed and parallel fashion, much like brains do.
The arguments against the proposition rely on a narrower definition of "computer" as a mindless
machine that executes pre-written programs and pretty much crash when something goes
wrong. Brains fall outside this very limited definition of "computer" for several reasons:
● Brains have bodies; of what use is disembodied thought and is it even possible?
● Brains give rise to emotion and consciousness.
● Brains work by pattern matching and prediction; computers follow prewritten scripts.
● Brains adapt to new environments.
Note that the the question only asks what arguments have been, or can be, put forward in
support or opposition to the proposition; they do not have to be true.
15.
Alan Turing is considered to be the founder of the field known as computer science due to
several contributions, perhaps the most notable of which is what is now known as the Universal
Turing Machine. The central idea of this idea is contribution is that the structure and operations
of mechanized versions of any computable algorithm can be encoded in such a way as to be
interpreted by a universal machine. This concept led directly to the stored-program computer,
whose impact on the world is hard to overestimate.
16.
The first computer that was both electronic and general purpose is widely considered to be the
ENIAC. From http://www.columbia.edu/cu/computinghistory/eniac.html:‘Later in 1945, the Army
circulated a call for "computers" for a new job with a secret machine. [Jean Jennings] Bartik
jumped at the chance and was hired as one of the original six programmers of ENIAC, the first
all-electronic, programmable computer. She joined Frances “Betty” Snyder Holberton, Kathleen
McNulty Mauchly Antonelli, Marlyn Wescoff Meltzer, Ruth Lichterman Teitelbaum and Frances
Bilas Spence in this unknown journey.’
17.
Aside from her pioneering compiler work in a variety of languages, Grace Murray Hopper’s
contributions to computer science include an instrumental role in the development of COBOL,
one of the most prominent business-oriented languages in the field, and the development of
the first standards for testing computer systems and components. She is also associated with
the etymology of the word “bug,” having frequently recounted a story where colleagues tracked
a computer program malfunction to a moth — a real “bug” — that was trapped in one of the
machine’s relays.
18.
This exercise involves choosing a school and answering questions specific to that school.
19.
An answer to this question depends on how revenue is actually counted. As long as sources
are cited and the revenue numbers explained, many answers are possible.
20.
Answers vary. One needs to find an article covering the influence of negative media portrayals
on computing professionals in keeping young people from the profession, and summarize its
claims.
21.
From Hatziapostolou, T., Kefalas, P., Sotiriadou, A., Promoting Computer Science Programmes
to Potential Students: 10 Myths for Computer Science, in Proceedings of the Informatics
Education Europe III Conference (IEEIII), Venice, Italy, December 4-5, 2008:
● Computer science is just web browsing, sending emails and using application programs.
● Computer science is just about programming.
● Computer science is just about math.
● Computer science undergraduate studies restrict one's choice of graduate studies.
● Computer science jobs are boring, lonely, and all taken.
● Computer science graduates never reach higher management positions.
● Computer science, information technology, and computer engineering are all the same.
● Computer science is only for men.
● Computer science is not as important to society and business as other fields.
● Computer science is only for nerds and geeks.
ANSWERS TO CHAPTER 2 EXERCISES
Programming in JavaScript:
Algorithms and Applications for Desktop and Mobile Browsers
1.
Writing a recipe can be considered programming because the author of the recipe has a goal in
mind and is writing instructions for an agent to carry out in order to achieve that goal. Some
people may object to the idea of cooks (professional or casual) as being "programmed" to carry
out a recipe. When we speak of people being programmed we are usually hinting at
brainwashing and similar unethical practices. The simple act of writing a recipe does not have
that affect on cooks. Perhaps if a cooking machine were built that could prepare recipes and
work reasonably well, recipe writing could be considered programming by nearly everyone.
2.
There are so many different meanings of script and program these days that the question is
hard to answer. But there is one set of definitions in which the analogy does hold. Some
people define programs as things written for users (e.g. Firefox, Microsoft Word, TurboTax),
while scripts are written for computer systems themselves to carry out mundane, behind the
scenes tasks like moving data around, doing backups, generating reports from log files, etc.
However, there are plenty of other definitions, many of which blur the distinction between
program and script, under which the analogy would not hold.
3.
Answers will vary, but here are some that might come up:
There were two nannies, one holding an umbrella and one not; using her finger, she
poked the first.
She performed a facebook poke on the nanny using an app on her smart phone she
calls "the umbrella."
(b) Looking through the telescope, I saw an astronomer who was standing on a hill.
I looked at that hill over there, and on that hill were two things, an astronomer and a
really big observatory with a telescope sticking out of the dome.
I looked at that hill over there, and on that hill was an astronomer, and the astronomer
was holding a little telescope.
(c) These little animals here called "time flies" enjoy eating an arrow for lunch.
See how long it takes the files to get from here to there the same way you measure how
long it takes an arrow to do the same.
This concept we call time, well, it is one dimensional, always advancing directly into the
future, kind of like how an arrow in flight doesn't boomerang.
(d) The City of Hershey prohibited the protest from going forward.
A group of chocolate bars made by the Hershey Corporation expressed their anger.
4. Examples include:
● Lawyers give poor free advice.
● Teacher strikes idle kids.
● Seven-foot doctors sue hospital.
● Stolen painting found by tree.
● Lack of brains hinder research.
● Millions of people live on water.
● The train left the station crowded and dirty.
● She ran to her sister with no shoes on.
● The enraged cow injured the farmer with the axe.
● They cooked for the first time on the stove.
5.
Type "programmable" into a web search engine; you'll see suggestions for thermostats, logic
controllers, and garage door remotes. Hundreds more examples exist.
6.
Answers vary, as this exercise asks for an essay.
7.
javascript:alert(1 + 4 + 8 + 16 + 25)
8.
javascript:alert(1000000/60/24/365.242199)
9.
The "official" list can be found at http://www.iana.org/assignments/uri-schemes.html. Among the
most common are: http, https, mailto, file, telnet, sms, urn, news, and ldap.
10.
The background of the input area turns yellow.
11.
The word blue appears below the input area and buttons.
12.
All page elements (text, buttons and input area) shifts to the right edge of the browser window.
13.
The script generates a random integer between 1 and 100 inclusive, then gives a user up to 10
tries to guess the number using a prompt. A correct guess immediately halts the script with a
success pop up. Each incorrect guess is followed a pop up informing the user whether the
guess was too small or too big.
14.
(a) 3.141592653589793
(b) 3.141592653589793
(c) true
(d) false
(e) 13
15.
<!doctype
html>
<html>
<head>
<meta
charset="UTF-‐8"/>
<title>Rolling
two
dice</title>
</head>
<body>
<p>You
rolled
a
<script>document.write(1
+
Math.floor(6
*
Math.random()))</script>
and
a
<script>document.write(1
+
Math.floor(6
*
Math.random()))</script>.</p>
</body>
</html>
16.
<!doctype
html>
<html>
<head>
<meta
charset="UTF-‐8"/>
<title>Rolling
two
20-‐sided
dice</title>
</head>
<body>
<p>You
rolled
a
<script>document.write(1
+
Math.floor(20
*
Math.random()))</script>
and
a
<script>document.write(1
+
Math.floor(20
*
Math.random()))</script>.</p>
</body>
</html>
17.
There are many possible answers, one of which is:
19.
<!doctype
html>
<html>
<head>
<meta
charset="UTF-‐8"/>
<title>JavaScript
Temperature
Converter</title>
</head>
<body>
<h1>Temperature
Conversion</h1>
<p>
<input
type="text"
id="temperature"
/>
<input
type="button"
id="kelvin"
value="F
to
K"
/>
<input
type="button"
id="fahrenheit"
value="K
to
F"
/>
</p>
<p
id="result"></p>
<script
src="temperature-‐kelvin.js"></script>
</body>
</html>
/*
*
This
script
goes
along
with
the
HTML
document
providing
a
converter
*
between
fahrenheit
and
kelvin.
*/
var
report
=
function
(kelvin,
fahrenheit)
{
document.getElementById("result").innerHTML
=
kelvin
+
"\xb0
K
=
"
+
fahrenheit
+
"\xb0
F";
};
document.getElementById("kelvin").onclick
=
function
()
{
var
fahrenheit
=
+document.getElementById("temperature").value;
report((fahrenheit
+
459.67)
/
1.8,
fahrenheit);
};
document.getElementById("fahrenheit").onclick
=
function
()
{
var
kelvin
=
+document.getElementById("temperature").value;
report(kelvin,
1.8
*
kelvin
-‐
459.67);
};
20.
<!doctype
html>
<html>
<head>
<meta
charset="UTF-‐8"/>
<title>JavaScript
Mass
Converter</title>
</head>
<body>
<h1>Mass
Conversion</h1>
<p>
<input
type="text"
id="mass"
/>
<input
type="button"
id="pounds"
value="kgs
to
lbs"
/>
<input
type="button"
id="kilograms"
value="lbs
to
kgs"
/>
</p>
<p
id="result"></p>
<script
src="mass.js"></script>
</body>
</html>
/*
*
This
script
goes
along
with
the
HTML
document
providing
a
converter
*
between
pounds
and
kilograms.
*/
var
POUNDS_PER_KILOGRAM
=
2.20462262;
var
report
=
function
(pounds,
kilograms)
{
document.getElementById("result").innerHTML
=
pounds
+
"lb
=
"
+
kilograms
+
"kg";
};
document.getElementById("kilograms").onclick
=
function
()
{
var
pounds
=
document.getElementById("mass").value;
report(pounds,
pounds
/
POUNDS_PER_KILOGRAM);
};
document.getElementById("pounds").onclick
=
function
()
{
var
kilograms
=
document.getElementById("mass").value;
report(kilograms
*
POUNDS_PER_KILOGRAM,
kilograms);
};
21.
<!doctype
html>
<html>
<head>
<meta
charset="UTF-‐8"/>
<title>JavaScript
Adder</title>
</head>
<body>
<h1>Addition</h1>
<p>
<input
type="text"
id="addend1"
/>
+
<input
type="text"
id="addend2"
/>
<input
type="button"
id="add"
value="="
/>
</p>
<p
id="result"></p>
<script
src="addition.js"></script>
</body>
</html>
/*
*
This
script
goes
along
with
the
HTML
document
for
an
adder.
*/
var
report
=
function
(addend1,
addend2,
sum)
{
document.getElementById("result").innerHTML
=
addend1
+
"
+
"
+
addend2
+
"
=
"
+
sum;
};
document.getElementById("add").onclick
=
function
()
{
var
addend1
=
+document.getElementById("addend1").value,
addend2
=
+document.getElementById("addend2").value;
report(addend1,
addend2,
addend1
+
addend2);
};
22.
((2
*
5)
-‐
(7
/
(-‐
6)))
+
4
(2
<
4)
||
(true
&&
false)
(1
<
2)
<
3
(!
x)
||
((!
y)
&&
z)
-‐
(-‐
4)
23.
There are multiple answers for each of these. Here are some rough ones:
(a) The sum of "The difference of '2 times 5' and the quotient of '7 and negative 6'" and 4
(b) Whether 2 < 4, or else: true is true and also false is true
(c) Whether the truth value of "one less than two", when treated as an integer, is less than
three
(d) Whether x is false, or else: y is not true and also z is true
(e) The negation of the negation of 4
24.
The line defining kilos can be removed and the initializing expression can be used in place of
the variable in the last line of the script. This cannot be done for meters, however, because it
appears twice in the final line. If the expression prompt("Enter
your
height
in
inches")
*
0.0254; were to be used for both occurrence of meters in the last line, the script would
prompt for the height twice.
25.
Answers vary. Decent arguments can be made for both sides of the question.
26.
The variable location is supplied by the host environment, in this case a web browser.
27.
var
miles
=
prompt("Enter
a
distance
in
miles");
alert(miles
+
"
miles
is
"
+
(miles
*
1.609344)
+
"
kilometers");
28.
The expected answer is something like the following:
/*
*
A
script
to
determine
the
width
of
the
universe
in
yottameters,
given
that
*
its
width
in
light
years
is
156
billion.
*/
var
WIDTH_IN_LIGHT_YEARS
=
156E9;
var
SPEED_OF_LIGHT_IN_METERS_PER_SECOND
=
299792458;
var
SECONDS_PER_YEAR
=
86400
/*
sec
per
day
*/
*
365.242199
/*
days
per
year
*/;
var
METERS_PER_LIGHT_YEAR
=
SPEED_OF_LIGHT_IN_METERS_PER_SECOND
*SECONDS_PER_YEAR;
var
YOTTAMETERS_PER_METER
=
1E-‐24;
var
WIDTH_IN_YOTTAMETERS
=
WIDTH_IN_LIGHT_YEARS
*
METERS_PER_LIGHT_YEAR
*
YOTTAMETERS_PER_METER;
alert("The
universe
is
"
+
WIDTH_IN_YOTTAMETERS
+
"
Ym
wide");
But some students may want to cram the whole solution into one line:
29.
Arguments for the proposition that software development is engineering:
● Programs are built to solve specific problems and meet specific constraints.
● Programs provide utility for their end users who often care little if at all for all the
decoration and flair used in authoring the (invisible to the end user) source code.
● Programs need to be reliable, scalable, robust, economical, correct, etc.
Arguments for the proposition that software development is a craft:
● Engineers create designs but don't often build the things they design; software
developers both design and build.
● Programming is an activity requiring great amounts of skill, and these skills are refined
and improved over years and years of practice.
● Programs are carefully built with tools by people who take pride in constructing them
according to their own preferences and often adding personal touches.
The above arguments are not complete nor even the best possible.
30.
The minimal amount of changes needed to satify JSLint results in:
A better version would place individual statements on their own lines, though:
var
x
=
0;
var
y
=
1;
var
sequence
=
[];
while
(y
<
1000)
{
sequence.push(y);
var
z
=
x
+
y;
x
=
y;
y
=
z;
}
alert(sequence);
31.
Answers vary.
32.
JavaScript was designed by Brendan Eich. It was originally called Mocha but its name was
changed to LiveScript before being first released in 1995. It was renamed "JavaScript,"
presumably as a marketing ploy to capitalize on the growing hype for another new language at
the time called Java. Java and JavaScript are completely unrelated despite having a small
number of superficial similarities.
33.
Answers here: http://javascript.crockford.com/javascript.html.
34.
Microsoft used the name JScript because "JavaScript" is a trademark. There are several
differences among the different versions of JavaScript; for example JavaScript versions 1.6-
1.8.x all add little experimental features to the language not found in the ECMAScript
specifications. JScript has some of its own, too. If programmers stick to the parts of the
language defined by ECMAScript then the JavaScript and JScript turn out to be the same.
35.
A fairly extensive list of products hosting a JavaScript engine can be found in Wikipedia's
JavaScript page in the section entitled "Uses outside web pages." A few products of note:
Adobe Photoshop, Adobe Illustrator, VRML 97, DX Studio, Maxwell Renderer, ChatZilla, and
XChat.