forked from gdi-curriculum-review/gdi-featured-js-intro-OLD
-
Notifications
You must be signed in to change notification settings - Fork 6
/
puzzles.html
480 lines (407 loc) · 20 KB
/
puzzles.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Puzzles</title>
<!-- <link rel="stylesheet" href="css/puzzles.css"> -->
<link href="js101-downloads/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="blog-header">
<h1 class="blog-title">JavaScript Puzzles</h1>
<p class="lead blog-description">Welcome! These are some bonus puzzles to accompany <a href="https://github.com/cfarm/intro-to-javascript">Intro to JavaScript</a> class. Please take a look at the puzzles, and work on one that looks challenging but not completely overwhelming. You can always reference <a href="http://cfarm.github.io/intro-to-javascript/">the slides</a> if you get stuck. Commit to spend at least 20 minutes trying to figure out a problem before you look at the answers. It helps you learn!</p>
<p></p>
</div>
<div class="row">
<div class="col-sm-8 blog-main">
<div class="blog-post">
<h2 class="blog-post-title" id="class1">Class 1</h2>
<h3 id="fortune">The Fortune Teller</h3>
<p><em>Why pay a fortune teller when you can just program your fortune yourself?</em></p>
<ul>
<li>Store the following into variables: city or place, job title, home, and hobby.</li>
<li>Output your fortune to the screen like so: "You will be a <u>_job_</u> living in a <u>_home_</u> in <u>_city or place_</u>. For fun you will <u>_hobby_</u>."</li>
</ul>
<button onclick="showSolution(1)">Show/Hide Solution</button>
<div class="codebox" id="example1Code">
<pre><code>
var jobTitle = 'web developer';
var home = 'sprawling beachfront treehouse';
var place = 'Costa Rica';
var hobby = 'play Scrabble';
var future = 'You will be a ' + jobTitle + ' living in a ' + home + ' in ' + place + '. For fun you will ' + hobby + '.'
console.log(future);
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="calculator">The Calculator</h3>
<ul>
<li>Write a function called <code>squareNumber</code> that will take one argument (a number), square that number, and return the result. It should also log a string like "The result of squaring the number 3 is 9." </li>
<li>Write a function called <code>halfNumber</code> that will take one argument (a number), divide it by 2, and return the result. It should also log a string like "Half of 5 is 2.5.".</li>
<li>Write a function called <code>percentOf</code> that will take two numbers, figure out what percent the first number represents of the second number, and return the result. It should also log a string like "2 is 50% of 4."</li>
<li>Write a function called <code>areaOfCircle</code> that will take one argument (the radius), calculate the area based on that, and return the result. It should also log a string like "The area for a circle with radius 2 is 12.566370614359172."
<ul><li>Bonus: Round the result so there are only two digits after the decimal.</li></ul>
</li>
<li>Write a function that will take one argument (a number) and perform the following operations, using the functions
you wrote earlier:
<ol>
<li>Take half of the number and store the result.</li>
<li>Square the result of #1 and store that result.</li>
<li>Calculate the area of a circle with the result of #2 as the radius.</li>
<li>Calculate what percentage that area is of the squared result (#3).</li>
</ol>
</li>
</ul>
<button onclick="showSolution(2)">Show/Hide Solution</button>
<div class="codebox" id="example2Code">
<pre><code>
function squareNumber(num) {
var squaredNumber = num * num;
console.log('The result of squaring the number ' + num + ' is ' + squaredNumber);
return squaredNumber;
}
squareNumber(3);
function halfOf(num) {
var half = num / 2;
console.log('Half of ' + num + ' is ' + half);
return half;
}
halfOf(5);
function percentOf(num1, num2) {
var percent = (num1/num2) * 100;
console.log(num1 + ' is ' + percent + '% of ' + num2);
return percent;
}
percentOf(5, 10);
function areaOfCircle(radius) {
var area = Math.PI * squareNumber(radius);
console.log('The area of circle with radius ' + radius + ' is ' + area);
return area;
}
areaOfCircle(2);
function doCrazyStuff(num) {
var half = halfOf(num);
var squared = squareNumber(half);
var area = areaOfCircle(squared);
var result = percentOf(squared, area);
}
doCrazyStuff(5);
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="string">Challenge Questions: String Manipulation</h3>
<p>If you feel comfortable with the other exercises, it's time to expand your knowledge! These puzzles involve manipulating strings; to try them out, you'll need to use some of the <a href="http://www.w3schools.com/jsref/jsref_obj_string.asp">built-in JavaScript methods for strings</a>. Methods are pre-written functions that are built into the language.</p>
<p>These questions are not as straightforward as the others. They challenge you to really think like a programmer. Really try to solve them before you peek at the answer.</p>
<h4>MixUp</h4>
<p>Create a function called <code>mixUp</code>. It should take in two strings, and return the concatenation of the two strings (separated by a space) slicing out and swapping the first 2 characters of each. You can assume that the strings are at least 2 characters long. For example:</p>
<pre>
mixUp('mix', pod'): 'pox mid'
mixUp('dog', 'dinner'): 'dig donner'
</pre>
<button onclick="showSolution(3)">Show/Hide Solution</button>
<div class="codebox" id="example3Code">
<pre><code>
//This function uses the slice() method. It extracts a part of a string and returns a new string
function mixUp(string1, string2) {
return string1.slice(0, 2) + string2.slice(2) + " " + string2.slice(0, 2) + string1.slice(2);
}
</code></pre>
</div>
<h4>FixStart</h4>
<p>Create a function called <code>fixStart</code>. It should take a single argument, a string, and return a version where all occurrences of its first character have been replaced with '*', except for the first character itself. You can assume that the string is at least one character long. For example:</p>
<pre>
fixStart('babble'): 'ba**le'
fixStart('turtle'): 'tur*le'
</pre>
<button onclick="showSolution(4)">Show/Hide Solution</button>
<div class="codebox" id="example4Code">
<pre><code>
//This function uses a few new methods and regular expressions
function fixStart(inputString) {
var firstChar = inputString.charAt(0);
return firstChar + inputString.slice(1).replace(new RegExp(firstChar, 'g'), '*');
}
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="bigger">What number is bigger?</h3>
<p>Write a function that compares two numbers and returns the larger one. Be sure to try it our with some different numbers. Bonus: add error messages if the numbers are equal or cannot be compared.</p>
<p>Don't forget to test it!</p>
<button onclick="showSolution(5)">Show/Hide Solution</button>
<div class="codebox" id="example5Code">
<pre><code>
function greaterNum(num1, num2) {
if (num1 === num2) {
console.log ('Those numbers are equal');
return num1;
} else if (num1 > num2) {
return num1;
} else if (num2 > num1) {
return num2;
} else {
console.log ('Those are simply incomparable!');
return undefined;
}
}
console.log (greaterNum(3, 3));
console.log (greaterNum(7, -2));
console.log (greaterNum(5, 9));
console.log (greaterNum(5, 'dog'));
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="pluralize">Pluralize</h3>
<p>Write a function <code>pluralize</code> that takes in two arguments, a number and a word, and returns the plural. For example:</p>
<pre>
pluralize(5, 'cat'): '5 cats'
pluralize(7, 'turtle'): '7 cats'
</pre>
<p>Bonus: Make it handle a few collective nouns like "sheep" and "geese".</p>
<button onclick="showSolution(6)">Show/Hide Solution</button>
<div class="codebox" id="example6Code">
<pre><code>
function pluralize(number, noun) {
if (number != 1 && noun != 'sheep' && noun != 'geese') {
return number + ' ' + noun + 's';
} else {
return number + ' ' + noun;
}
}
console.log('I have ' + pluralize(0, 'cat'));
console.log('I have ' + pluralize(1, 'cat'));
console.log('I have ' + pluralize(2, 'cat'));
console.log('I have ' + pluralize(3, 'geese'));
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="evenodd">Even/Odd Counter</h3>
<p>Write a for loop that will iterate from 0 to 20. For each iteration, it will check if the current number is even or odd, and report that to the screen (e.g. "2 is even")</p>
<button onclick="showSolution(7)">Show/Hide Solution</button>
<div class="codebox" id="example7Code">
<pre><code>
for (var i = 0; i <= 20; i++) {
if (i % 2 === 0) {
console.log(i + ' is even');
} else {
console.log(i + ' is odd');
}
}
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="topchoice">Top Choice</h3>
<p>Create an array to hold your top choices (colors, presidents, whatever). For each choice, log to the screen a string like: "My #1 choice is blue." Bonus: Change it to log "My 1st choice, "My 2nd choice", "My 3rd choice", picking the right suffix for the number based on what it is.</p>
<button onclick="showSolution(8)">Show/Hide Solution</button>
<div class="codebox" id="example8Code">
<pre><code>
var choices = ['red', 'orange', 'pink', 'yellow'];
for (var i = 0; i < choices.length; i++) {
console.log('My #' + (i + 1) + ' choice is ' + choices[i]);
}
for (var i = 0; i < choices.length; i++) {
var choiceNum = i + 1;
var choiceNumSuffix;
if (choiceNum == 1) {
choiceNumSuffix = 'st';
} else if (choiceNum == 2) {
choiceNumSuffix = 'nd';
} else if (choiceNum == 3) {
choiceNumSuffix = 'rd';
} else {
choiceNumSuffix = 'th';
}
console.log('My ' + choiceNum + choiceNumSuffix + ' choice is ' + choices[i]);
}
</code></pre>
</div>
<h2 id="class2">Class 2</h2>
<h3 id="reading">The Reading List</h3>
<p>Keep track of which books you read and which books you want to read!</p>
<ul>
<li>Create an array of objects, where each object describes a book and has properties for the title (a string), author (a string), and alreadyRead (a boolean indicating if you read it yet).</li>
<li>Iterate through the array of books. For each book, log the book title and book author like so: "The Hobbit by J.R.R. Tolkien".</li>
<li>Now use an if/else statement to change the output depending on whether you read it yet or not. If you read it, log a string like 'You already read "The Hobbit" by J.R.R. Tolkien', and if not, log a string like 'You still need to read "The Lord of the Rings" by J.R.R. Tolkien.'</li>
</ul>
<button onclick="showSolution(9)">Show/Hide Solution</button>
<div class="codebox" id="example9Code">
<pre><code>
var books = [
{title: 'The Design of EveryDay Things',
author: 'Don Norman',
alreadyRead: false
},
{title: 'The Most Human Human',
author: 'Brian Christian',
alreadyRead: true
}];
for (var i = 0; i < books.length; i++) {
var book = books[i];
var bookInfo = book.title + '" by ' + book.author;
if (book.alreadyRead) {
console.log('You already read "' + bookInfo);
} else {
console.log('You still need to read "' + bookInfo);
}
}
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="logo">Logo Hijack</h3>
<ul>
<li>Open up <a href="http://www.google.com">www.google.com</a> in Chrome or Firefox, and open up the console.</li>
<li>Find the Google logo and store it in a variable.</li>
<li>Modify the source of the logo IMG so that it's a Yahoo logo instead. (http://www.logostage.com/logos/yahoo.GIF)</li>
<li>Find the Google search button and store it in a variable.</li>
<li>Modify the text of the button so that it says "Yahooo!" instead.</li>
</ul>
<button onclick="showSolution(10)">Show/Hide Solution</button>
<div class="codebox" id="example10Code">
<pre><code>
var img = document.getElementById('hplogo');
img.width = 400;
img.src = 'http://www.logostage.com/logos/yahoo.GIF';
var button = document.getElementById('gbqfba');
button.innerHTML = 'Yahoooo!';
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="reading2">The Reading List Part II</h3>
<ul>
<li>Create a webpage with an <code>h1</code> of "My Book List".</li>
<li>Add a script tag to the bottom of the page, where all your JS will go.</li>
<li>Copy the array of books from the previous exercise.</li>
<li>Iterate through the array of books. For each book, create a <code>p</code> element with the book title and author and append it to the page.</li>
<li><strong>Bonus</strong>: Use a <code>ul</code> and <code>li</code> to display the books.</li>
<li><strong>Bonus</strong>: add a property to each book with the URL of the book cover, and add an <code>img</code> element for each book on the page.</li>
<li><strong>Bonus</strong>: Change the style of the book depending on whether you have read it or not.</li>
</ul>
<button onclick="showSolution(11)">Show/Hide Solution</button>
<div class="codebox" id="example11Code">
<pre><code>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Book List</title>
</head>
<body>
<h1>My Book List</h1>
<script>
var books = [
{title: 'The Design of EveryDay Things',
author: 'Don Norman',
alreadyRead: false
},
{title: 'The Most Human Human',
author: 'Brian Christian',
alreadyRead: true
}];
for (var i = 0; i < books.length; i++) {
var bookP = document.createElement('p');
var bookDescription = document.createTextNode(books[i].title + ' by ' + books[i].author);
bookP.appendChild(bookDescription);
document.body.appendChild(bookP);
}
// Or, with the bonuses:
var books = [
{title: 'The Design of EveryDay Things',
img: 'http://ecx.images-amazon.com/images/I/41j2ODGkJDL._AA115_.jpg',
author: 'Don Norman',
alreadyRead: false
},
{title: 'The Most Human Human',
img: 'http://ecx.images-amazon.com/images/I/41Z56GwEv9L._AA115_.jpg',
author: 'Brian Christian',
alreadyRead: true
}];
var bookList = document.createElement('ul');
for (var i = 0; i < books.length; i++) {
var bookItem = document.createElement('li');
var bookImg = document.createElement('img');
bookImg.src = books[i].img;
bookItem.appendChild(bookImg);
var bookDescription = document.createTextNode(books[i].title + ' by ' + books[i].author);
bookItem.appendChild(bookDescription);
if (books[i].alreadyRead) {
bookItem.style.color = 'grey';
}
bookList.appendChild(bookItem);
}
document.body.appendChild(bookList);
</script>
</body>
</html>
</code></pre>
</div>
<p><br><a href="#">Back to top</a></p>
<h3 id="counter">Challenge Question: The Counter</h3>
<p>Write a function that takes a certain type of tag and counts the number of elements with that tag. The function should return "There a X tags of type y on the page.For example:</p>
<pre>
countTags('p'): 'There are 3 tags of type p on the page'
</pre>
<button onclick="showSolution(12)">Show/Hide Solution</button>
<div class="codebox" id="example12Code">
<pre><code>
function countTags (tagType) {
var tagArray = document.getElementsByTagName(tagType);
console.log ('There are ' + tagArray.length + ' tags of type ' + tagType + ' on the page.');
}
</code></pre>
</div>
</div><!-- /.blog-post -->
<p>
<br><a href="#">Back to top</a>
</p>
</div><!-- /.blog-main -->
<div class="col-sm-3 col-sm-offset-1 blog-sidebar">
<div class="sidebar-module sidebar-module-inset">
<h4>Puzzles</h4>
<nav class="blog-nav">
<h5><a class="blog-nav-item" href="#class1">Class 1</a></h5>
<ul>
<li><a class="blog-nav-item" href="#fortune">The Fortune Teller</a></li>
<li><a class="blog-nav-item" href="#calculator">The Calculator</a></li>
<li><a class="blog-nav-item" href="#string">String Manipulation</a></li>
<li><a class="blog-nav-item" href="#bigger">What number is bigger?</a></li>
<li><a class="blog-nav-item" href="#pluralize">Pluralize</a></li>
<li><a class="blog-nav-item" href="#evenodd">Even/Odd Counter</a></li>
<li><a class="blog-nav-item" href="#topchoice">Top Choice</a></li>
</ul>
<h5><a class="blog-nav-item" href="#class2">Class 2</a></h5>
<ul>
<li><a class="blog-nav-item" href="#reading">The Reading List</a></li>
<li><a class="blog-nav-item" href="#logo">Logo Hijack</a></li>
<li><a class="blog-nav-item" href="#reading2">The Reading List Part II</a></li>
<li><a class="blog-nav-item" href="#counter">The Counter</a></li>
</ul>
</nav>
</div>
<div class="sidebar-module sidebar-module-inset">
<p>Puzzle and code by Sylvia Richardson and Pamela Fox. This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/deed.en_US">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.</p>
</div>
</div><!-- /.blog-sidebar -->
</div><!-- /.row -->
</div><!-- /.container -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
// Powers show/hide buttons.
$( document ).ready(function() {
$("div.codebox").hide();
});
function showSolution(num) {
$("div#example" + num + "Code").toggle();
}
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-39435329-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>