Start Programming Using HTML, CSS, and JavaScript

Quiz, Additional Problems, and Source Code

Question 1
HTML is a ___ language.
Question 2
Which one of the following elements is used for headings?
Question 3
Which one of the following attributes is used for referencing image files?
Question 4
A void element doesn't need a closing tag.
Question 5
What kind of elements insert line breaks into a web page?
Question 6
Is it a good idea to insert text directly into the <body> element?
Question 7
Which one of the following lines of code is equivalent to <img src="C1984.jpg" alt="Class of '84">?
Question 8
Which one of the following lines of HTML code is correct?
Question 9
Which one of the following elements is a block element?
Question 10
Which one of the following lines of code is correct?
Question 11
checked is a Boolean attribute that is used when you want a certain checkbox or radio control to be selected by default. Which one of the following lines is the correct syntax for the checked attribute?
Question 12
Which one of the following lines of code does not represent a void element?
Question 1
HTML is used to ___.
Question 2
Which of the following elements are allowed to contain block elements?
Question 3
Which one of the following lines of HTML code is correct?
Question 4
Which one of the following elements cannot appear directly inside the <table> element?
Question 5
Which one of the following HTML elements is a generic element?
Question 6
Which one of the following HTML elements is a sectioning element?
Question 7
You can hide a subheading from the document outline using the ___ element.
Question 8
The URL /maps/europe.html is a(n) ___ URL.
Question 9
Which one of the following lines of code is a hyperlink from a thumbnail koala_thumb.jpg to a full-size photo koala.jpg?
Question 10
What is the correct syntax for a character entity?
Question 1
CSS is a ___ language.
Question 2
CSS rules can only be used with internal or external style sheets.
Question 3
What is the correct HTML for including an external style sheet?
Question 4
Which one of the following lines of code is a correct CSS rule?
Question 5
Consider the following two CSS declarations:
  font-style: italic;
  font: bold 20px Helvetica, sans-serif;
						
Which font style will be used after the declarations have been applied?
Question 6
Which one of the following lines of CSS code has an error in it?
Question 7
How do you write comments in a CSS file?
Question 8
Which part of a CSS rule specifies which parts of an HTML document should be styled?
Question 1
What is the correct HTML syntax for using a class selector?
Question 2
What is the correct CSS syntax to define a class?
Question 3
Which one of the following selectors selects all the <h1> and <h2> elements?
Question 4
Which one of the following selectors selects all the <b> elements that have their class attribute set to definition?
Question 5
Every child of an element is also a descendant of that element and every descendant of an element is also a child of that element.
Question 6
Not all of the CSS properties are automatically inherited.
Question 7
Which one of the following selectors is the most specific?
Question 8
Percentages work in exactly the same way as ems do.
Question 9
When using percentages, the size of vertical margins is calculated based on the ___ of the containing block.
Question 10
Suppose that you set the width of an element to 2 em. What will be the actual width of that element?
Question 1
The background color of an element doesn't expand under the ___.
Question 2
Paddings provide white space between elements.
Question 3
The display property of an element is set to inline. Which one of the following statements is true?
Question 4
Vertical margins of absolutely positioned element's don't collapse.
Question 5
The containing block of an absolutely positioned element is specified by that element's ___.
Question 6
Which one of the following CSS declarations doesn't take an element out of the flow?
Question 7
A floated element is taken out of the flow but text and inline elements still respect its presence.
Question 8
Consider the following set of CSS rules:
  a:link { color: blue; }
  a:hover { color: orange; }
  a:visited { color: black; }
						
Is the order of the rules correct?
Question 9
Which one of the following selectors selects the first child of a paragraph?
Question 1
Which one of the following identifiers is a valid JavaScript name?
Question 2
JavaScript is case sensitive.
Question 3
Which one of the following JavaScript expressions is not a literal?
Question 4
What is the type of the value 0xf4?
Question 5
Which one of the following expressions is not of the number type?
Question 6
Which one of the following operators has the lowest precedence?
Question 7
Which one of the following expressions returns true?
Question 8
What value does the expression 1 - 2 * 2 return?
Question 9
What value does the expression 18 % 8 / 4 return?
Question 10
Suppose x has been assigned the value 51. What value does the expression x > 10 && x < 51 return?
Question 11
What value does the expression "8" > "45" return?
Question 12
Consider the following JavaScript code fragment:
  var x = 10;
  x % 6;
						
What will be the value of x after the code has been executed?
Question 13
Consider the following JavaScript code fragment:
  var x = 10;
  x %= 6;
						
What will be the value of x after the code has been executed?
Question 14
Consider the following JavaScript code fragment:
  var x = 10, y;
  y = 7 + --x;
						
What will be the value of y after the code has been executed?
Question 15
The expression x > 0 ? 0 : -x returns the value 20. What is the possible value of x?
Question 1
Consider the following JavaScript code fragment:
  var x = 1, y;
  if (x != 1)
    y = 1;
    x++;
						
What will be the value of x after the code has been executed?
Question 2
Consider the following JavaScript code fragment:
  var x = 1, y;
  if (x != 1)
    y = 1;
    x++;
  else
    x = 10;
						
What will be the value of x after the code has been executed?
Question 3
Consider the following JavaScript code fragment:
  var x = 1;
  if (x == 1) x = 2;
  if (x == 2) x = 1;
						
What will be the value of x after the code has been executed?
Question 4
Which one of the following values is a truthy value?
Question 5
Assume that x has been assigned a nonnegative integer. What will be the value of x after the statement while (x--); has been executed?
Question 6
Which one of the following code fragments will sum the integers from 1 to 10?
Question 7
If you want your program to pause during a debugging process, you need to set a ___.
Question 8
Which one of the following expressions returns NaN?
Question 9
Suppose x has been assigned the string value "1". Which one of the following expressions doesn't return the value 2?
Question 10
Suppose x has been assigned the string value "1". What value will the expression Number("x") return?
Question 11
The equality operator (==) treats the values null and undefined as equal.
Question 12
Which one of the following expressions returns true?
Question 13
The expressions "x" > 0 and "x" < 0 return different values.
Question 1
Consider the following switch statement:
  switch (x) {
  case 1: y = 10; break;
  default: y = 20;
  }
						
Which one of the following statements has exactly the same effect as the above code?
Question 2
Which one of the following expressions is a possible way of accessing the E property of the Math object?
Question 3
Which one of the following expressions returns 1?
Question 4
Which one of the following expressions returns a random integer between 5 and 10 inclusive?
Question 5
Suppose x has been assigned the value 0. Which one of the following lines of code changes this value?
Question 6
Consider the following line of code:
  var d = new Date();
						
Which one of the following expressions returns the current day of the week?
Question 7
You don't have to create an object instance in order to call static methods.
Question 8
How can you compute how much time has passed between two time stamps specified by two Date object instances dt1 and dt2?
Question 9
Which one of the following lines constructs a Date object whose year field is equal to 2020?
Question 1
Consider the following JavaScript code:
  var date1 = new Date();
  var date2 = date1;
  date2.setFullYear(date2.getFullYear() + 1);
						
After the code has been executed, what value does the expression date1.getFullYear() == date2.getFullYear() return?
Question 2
Consider the following declaration:
  var a = new Array(6);
						
What value does the expression a.length return?
Question 3
Consider the following declaration:
  var a = [6];
						
What value does the expression a[0] return?
Question 4
Consider the following JavaScript code:
  var a = [1, 2, 3];
  a[a.length] = 4;
						
Which one of the following expressions returns 4?
Question 5
Consider the following JavaScript code:
  var sum = 0, i;
  for (i = 1; i == 4; i++) {
    sum += 2 * i;
  }
						
After the code has been executed, what is the value of sum?
Question 6
Consider the following JavaScript code:
  var sum = 0, i;
  for (i = 1; /* missing expression */; i++) {
    sum += 2 * i;
  }
						
Which one of the following expressions should be inserted into the code so that sum will have the value of 20 after the code has been executed?
Question 7
Consider the following JavaScript code:
  var f = 1, i;
  for (i = 5; i > 0; /* missing expression */ ) {
    f *= i;
  }
						
Which one of the following expressions should be inserted into the code so that f will have the value of 120 after the code has been executed?
Question 8
Consider the following JavaScript code:
  var x = 0, y = 0;
  (x = 1) || (y = 1);
						
What will be the values of x and y after the code has been executed?
Question 9
Consider the following JavaScript code:
  var a = [2, 1, 1, 3, 5];
  var i, b = [];
  for (i = a.length - 1; i >= 0; i--) {
    b[i] = a[i];
  }
						
What will be the contents of the array b after the code has been executed?
Question 10
Consider the following JavaScript code:
  var a = [2, 1, 1, 3, 5];
  var b = [12, 6, -15, 9, 100, 101];
  var i, c = [];
  for (i = a.length - 1; i >= 0; i--) {
    c[i] = b[a[i]];
  }
						
What will be the contents of the array c after the code has been executed?
Question 11
What is the value of the expression [1, 7, 12, 5, 103, 42, 103].sort().indexOf(103)?
Question 12
What is the value of the expression [4, 7, 9, 12, -5].reverse()[1]?
Question 13
Consider the following JavaScript code:
  var str = "jelly";
  str[0] = "b";
  
						
What will be the value of str after the code has been executed?
Question 14
Consider the following JavaScript code:
  var s = "What    must  be,  must be.     "
  var i, cleaned = "";
  for (i = 0; i < s.length; i++) {
    if ( /* missing code */ ) {
      cleaned += s[i];
    } 
  }						
Which one of the following lines of code should you use so that the above code will replace any contiguous whitespace inside s with a single whitespace character (i.e., the value of cleaned should be "What must be, must be. ")?
Question 15
Consider the following JavaScript code:
  var a = [[1, 2], [3, 4, 5], [6, 7]];
  var i, j = 1, sum = 0;
  for (i = 0; i < a[j].length; i++) {
    sum += a[j][i];
  }
						
After the code has been executed, what is the value of sum?
Question 1
In JavaScript, it is always possible to call a function before it is defined because a function definition is always hoisted.
Question 2
Which one of the following expressions is a function expression?
Question 3
Which one of the following function definitions is syntactically wrong?
Question 4
Consider the following function definition:
  var sum = function(a, b) {
    return a + b;
  };
						
Which one of the following expressions returns the sum of the numbers 1, 2, and 3?
Question 5
Consider the following function definition:
  var sum = function(a, b) {
    return a + b;
  };
						
Which one of the following expressions returns the sum of the numbers 1, 2, 3, and 4?
Question 6
Consider the following function definition:
  var f = function(x1, x2) {
    return arguments.length;
  };
						
What is the value of the expression f()?
Question 7
Consider the following JavaScript code:
  var f = function() {
    return 4;
  };
  var x = f;
						
After the code has been executed, which one of the following expressions returns 4?
Question 8
Consider the following JavaScript code:
  var f = function() {
    return 4;
  };
  var x = f();
						
After the code has been executed, which one of the following expressions returns 4?
Question 9
Consider the following JavaScript code:
  var f1 = function() {
    var x = 1;
  };
  var f2 = function() {
    x = 1;
  };
  var x;
  /* invoke one of the above functions */
  console.log(x);
						
Which one of the two functions f1() and f2() should be invoked so that the number 1 will be written to the Console?
Question 10
Consider the following JavaScript code:
  var f1 = function() {
    var x = 1;
  };
  var f2 = function(x) {
    x = 1;
  };
  var x;
  /* invoke one of the above functions */
  console.log(x);
						
Which one of the two functions f1() and f2() should be invoked so that the number 1 will be written to the Console?
Question 11
Suppose that you have a function definition with two named parameters x1 and x2 (in that order). Which one of the following statements is not true?
Question 12
Consider the following JavaScript code:
  var nextDay = function(d) {
	d.setDate(d.getDate() + 1);
  };
  someday = new Date(2017, 0, 31);
  nextDay(someday);
						
After the code has been executed, what date will be stored in someday?
Question 13
Consider the following JavaScript code:
  var nextDay = function(d) {
	d = new Date(2017, 1, 1);
  };
  someday = new Date(2017, 0, 31);
  nextDay(someday);
						
After the code has been executed, what date will be stored in someday?
Question 14
Consider the following JavaScript code:
  var count = function(start) {
    return function() {
	  start++;
	  return start;
    };
  };
  var x = count(3);
  var y = count(5);
  x();
						
After the code has been executed, which one of the following expressions will return true?
Question 15
Consider the following JavaScript code:
  var count = function(start) {
    return function() {
	  start++;
	  return start;
    };
  };
  var x = count(3);
  var y = count(5);
  x();
  x();
						
After the code has been executed, which one of the following expressions will return true?
Question 1
Consider the following declaration:
  var block = {width: 3.1, length: 6.0, height: 4.3};
						
Which one of the following expressions that modify the height of the block contains an error?
Question 2
Consider the following declaration:
  var block = {width: 3.1, length: 6.0, height: 4.3};
						
Which one of the following expressions contains an error?
Question 3
Consider the following JavaScript code:
  var v = {x: -12};
  var x = "y";
  v[x] = 10;
						
What is the value of the expression v.y?
Question 4
Consider the following JavaScript code:
  var v = {x: -12};
  v[x] = 10;
						
What is the value of the expression v.x?
Question 5
Assume that you want to define a constructor for your own class of objects. Which one of the following statements is true?
Question 6
A static method can use the this keyword to access any object instance of the class that it belongs to.
Question 7
Assume that you have defined a class MyClass, to which you add the following definition:
  MyClass.prototype.myMethod = function(x) {
    this.x = x;						  
  };
						
The this keyword inside the body of the above definition is a reference to ___
Question 8
An invocation context is just another word for scope.
Question 9
Consider the following JavaScript code:
  var Test = function() {};
  Test.x = function() {};
  Test.prototype.y = function() {};
  var test = new Test();						
						
Which one of the following expressions is correct?
Question 10
Consider the following JavaScript code:
  var A = function() {
    this.x = 8;
  };  
						
After the code has been executed, which one of the following lines of code writes 8 to the Console?
Question 11
Consider the following JavaScript code:
  var A = function(val) {
    this.value = val;
  };
  A.prototype.getValue = function() {
    return this.value;
  };
  var Q = function() {
    var a = new A("a");
    var b = a.getValue();
  };
  Q(); 
						
When the getValue() method is invoked, which object does this refer to from within the method body?
Question 12
Consider the following JavaScript code:
  var A = function(val) {
    this.value = val;
  };
  A.prototype.getValue = function() {
    return this.value;
  };
  var Q = function() {
    var a = new A("a");
    var b = a.getValue;
    b();
  };
  Q();
						
When the getValue() method is invoked, which object does this refer to from within the method body?
Question 1
If you want your JavaScript code to execute asynchronously, you should put it ___
Question 2
The this keyword, when used inside the onload event handler of the Window object, refers to the ___
Question 3
Consider the following function definition:
  var myHandler = function() {
    /* Do something here */
  };
						
Suppose that you want this function to execute every time when a visitor clicks the element referenced by el. How can you do that?
Question 4
Consider the following HTML code:
  <span id="fill-this-out"></span>
						
Which one of the following lines of JavaScript code will write some text inside the above <span> element?
Question 5
If you want to display a live clock on your page, you can animate it using ___
Question 6
Consider the following CSS rule:
  .selected {
    border-style: solid;
  }
						
Which one of the following lines of JavaScript code will produce a border around the element referenced by el?
Question 7
Which one of the following HTML attributes has a different name when used as a JavaScript property?
Question 1
Consider the following HTML code:
  <section>
    <h2>Heading</h2>
    <p>Paragraph1</p>
    <p>Paragraph2</p>
  </section>
						
The following JavaScript code is used to get a reference to the above <section> element:
  var sec = document.getElementsByTagName("section");
						
Which one of the following JavaScript expressions returns the string "Paragraph2"?
Question 2
Consider the following HTML code:
  <section>
    <h2>Heading</h2>
    <p>Paragraph1</p>
    <p>Paragraph2</p>
  </section>
						
The following JavaScript code is used to get a reference to the above <section> element:
  var sec = document.getElementsByTagName("section")[0];
						
Which one of the following JavaScript expressions returns the string "Paragraph2"?
Question 3
Consider the following HTML code:
  <section>
    <h2>Heading</h2>
    <p>Paragraph1</p>
    <p>Paragraph2</p>
  </section>
						
The following JavaScript code is used to extract information from the above HTML:
  var str = "";
  var sec = document.getElementByTagName("section")[0]; 
  var el = sec.firstElementChild;
  while (el) {
    str += el.innerHTML[0];
	el = el.nextElementSibling;
  }
						
After the code has been executed, what is the contents of the string str?
Question 4
The createElement() method creates an element and inserts it into the document tree.
Question 5
Consider the following HTML code:
  <section>
    <h2>Heading</h2>
    <p>Paragraph1</p>
    <p>Paragraph2</p>
  </section>
						
What will be the effect of the following JavaScript code?
  var sec = document.getElementsByTagName("section")[0];
  var ch = sec.removeChild(sec.lastElementChild);
  sec.insertBefore(ch, sec.lastElementChild);
						
Question 6
It is not safe to add custom properties and methods to DOM objects.
Question 7
You can pass arguments to an event-handler function ___
Question 8
Which one of the following HTML attributes has a different capitalization when used as a JavaScript property?
Challenge 1

Write a program that computes the factorial of n. The factorial of n is the product of all positive integers less than or equal to n and is denoted by n!.

For example: 4! = 1×2×3×4 = 24

By definition, zero factorial is equal to one: 0! = 1.

Get solution
Challenge 2

Write a program that counts from 1 to 100 but replaces any number divisible by three with the word "Fizz" and any number divisible by five with the word "Buzz". If a number is divisible by both, three and five, the program should replace it with "FizzBuzz".

The program output should look like this: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, ...

An interesting fact about the Fizz Buzz problem is that it is commonly used as a job interview question that helps ruling out more than 95% of programmer candidates. Allegedly, the problem is so hard for many people because its solution doesn't follow any of the standard patterns taught in schools.

Get solution
Challenge 3

Implement a base-n counter for any n between 2 and 10.

Base-n counting is like usual counting except that you use a different number of digits. Basically, each counting step starts by incrementing the rightmost digit by one. If the digit cannot be incremented any further, the digit is set back to zero, and its left nearest neighbor is incremented by one. This continues until either a digit can be incremented or all the digits are set back to zero and the digit 1 is added to the left of the counter.

For example, a base-2 (binary) counter counts like: 0, 1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010, 1011, 1100, ...

A base-4 counter would go as: 0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33, 100, 101, 102, 103, 110, ...

In everyday counting we use a base-10 (decimal) counting: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...

Hint: You can convert any base-10 number to its base-n representation by simply collecting all the remainders of consecutive divisions of that number by n.

Get solution
Challenge 1

Write a program that, given a number of elapsed milliseconds, writes the elapsed time in hh:mm:ss.f format.

For example, for 129619 milliseconds the program should display 00:02:09.6.

Get solution
Challenge 2

Write a program that computes the value of π = 3.14159... using the Leibniz formula π = 4 - 4/3 + 4/5 - 4/7 + 4/9 - ...

Notice that the Leibniz formula is an infinite series, so you will have to decide to stop it at some point to get an approximation of π.

Get solution
Challenge 3

Write a program that finds an approximate solution to the following problem: A jar contains two green and five red marbles. You take a random marble from the jar and then you take a second random marble without replacing the first one. What is the probability that none of the two chosen marbles is green ? (The exact answer is 10/21)

Hint: You can simulate the action of taking two random marbles from the jar for, say, 100,000 times, counting the number of times when no green marble is chosen. Finally, you compute the probability by simply dividing the number of times when no green marble is chosen by the total number of trials (i.e., 100,000).

Get solution
Challenge 1

Write a program that computes and outputs the first 20 Fibonacci numbers. The first two Fibonacci numbers are zero and one, and each following number is the sum of the previous two.

For example, the first 10 Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

Get solution
Challenge 2

Write a program that makes a copy of an array of integers with all the duplicates removed.

Get solution
Challenge 3

The following code selects six different random numbers from one to 54 inclusive and stores them into an array numbers:

  var numbers = [];
  var i, n;
  for (n = 0; n < 6; n++) {
    do {
      numbers[n] = Math.floor(Math.random() * 54) + 1;
    } while(numbers.indexOf(numbers[n]) < n);
  }
  console.log(numbers);
						

The solution uses an array (numbers), two numerical variables (i and n), and two loops. Rewrite the program so that you only use an array, a single numerical variable, a single loop, and an if statement.

Hint: Look for additional properties and methods of the Array object.

Get solution
Challenge 4

Write a program that corrects two initial capitals in a string. For example, a string "TWo INitial CApitals" should be corrected to "Two Initial Capitals".

Get solution
Challenge 5

Write a program that evaluates expressions using Reverse Polish Notation (RPN). Assume that only decimal digits (from 0 to 9) are used as operands and only addition, subtraction, multiplication, and division are used as operations.

RPN is a way of writing mathematical expressions where each operator follows all of its operands. For example, the algebraic expression 5 + 8 is written as 5 8 + in RPN.

When evaluating an RPN expression, you often use a stack, which is an abstract data type used for storing a collection of elements. You store an element to a stack by simply putting that element on top of the stack, and you retrieve an element from a stack by taking the element that is currently on the top of the stack. The two operations on a stack are called push and pop, respectively. In JavaScript, you can use an Array object to implement a stack, using the object's push() and pop() methods to store and retrieve elements.

To evaluate an RPN expression, you only need to carry out two activities:

  • If there is a value in the expression, push that value onto the stack.
  • If an operator appears in the expression, first pop two values off the top of the stack (assuming the operator is binary) and push the result of the operation back onto the stack.

When the end of the expression is reached, there should be a single value left on the stack, which is the final value of the expression.

Note that—if you only use binary operators—there should be exactly one operand more than there are operators in a valid RPN expression. It is also true that on the left side of any point within an RPN expression there should be at least one operand more than there are operators.

For example, the expression 5 9 4 + 2 - * is evaluated as follows:

  • 5 (push 5 onto the stack), stack contents: 5
  • 9 (push 9 onto the stack), stack contents: 5 9
  • 4 (push 4 onto the stack), stack contents: 5 9 4
  • + (pop the values 4 and 9 off the stack, add the values, and push the result back onto the stack), stack contents: 5 13
  • 2 (push 2 onto the stack), stack contents: 5 13 2
  • - (pop the values 2 and 13 off the stack, subtract the values, and push the result back onto the stack), stack contents: 5 -11
  • * (pop the values -11 and 5 off the stack, multiply the values, and push the result back onto the stack), stack contents: -55 (this is now the value of the above RPN expression)
Get solution
Challenge 1

The following JavaScript code produces a histogram displaying a distribution of the sums obtained by rolling two dice for 100 times:

  var sums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 
  var i;
  for (i = 0; i < 100; i++) {
    sums[sumOfNDice(2) - 2]++;
  }
  for (i = 0; i < sums.length; i++) {
    console.log(histogram(i + 2, sums[i]));
  }
						

Write the missing definitions of the functions sumOfNDice() and histogram().

The function sumOfNDice() takes as a parameter a positive integer n. The function rolls n dice and returns their sum.

The function histogram() takes two parameters, legend and value. The function returns a string containing legend, a colon, and value hash symbols (#).

Finally, a completed program should produce a histogram like this one:

 2: #
 3: ##
 4: ###########
 5: #############
 6: ############
 7: ##################
 8: ####################
 9: ##############
10: #######
11: 
12: ##
						
Get solution
Challenge 2

Write a program that finds the solution to the following problem. Using the digits 3, 3, 8, and 8 each once and only once, and using (some or all of the operations of) addition, subtraction, multiplication, division, and parentheses, build an expression that evaluates to 24.

Hint: With the help of a base-n counter (see Meeting 7, Challenge 3) build all the possible strings of length 7 using some or all of the symbols "3", "8", "+", "-", "*", and "/" (you will use a base-6 counter). Then, using a RPN calculator (see Meeting 9, Challenge 5), evaluate each one of the before obtained strings as RPN expressions. An expression that evaluates to 24 and has exactly two 3's and two 8's is the solution to the problem.

Get solution
Challenge 1

Define a class named Box that will allow you to construct a box (i.e., rectangular cuboid) with sides a, b, and c. The class should implement two methods, one that will return the volume of the box and one that will test whether or not the box fits into another box (passed as a parameter).

This is an example of using the Box class:

  var boxOne = new Box(1, 4, 9);
  var boxTwo = new Box(2, 8, 0.6);
  console.log(boxOne.getVolume()); //Writes 36
  console.log(boxTwo.fitsInto(boxOne)); //Writes true
						
Get solution
Challenge 2

Extend the String class with a method correctTwoInitialCapitals() that corrects two initial capitals in a string (see Meeting 9, Challenge 4).

This is an example of using the method:

  var testString = "THis is an (EXample).";
  console.log(testString.correctTwoInitialCapitals()); //Writes This is an (Example).
						
Get solution
Challenge 3

Write a program that solves a classic knapsack problem: Assume that you have a knapsack that can hold a certain maximum weight. Given a number of items, each having a mass and value, determine which items to pack into the knapsack so that their total value is as large as possible while their total weight does not exceed the knapsack capacity.

To solve the problem, define a class Knapsack, whose usage is shown in the following code:

  var i;
  var myKnapsack = new Knapsack(99); //The maximum weight (the knapsack capacity) is 99
	
  myKnapsack.insertItem(new Item(23, 34));
  myKnapsack.insertItem(new Item(77, 65));
  myKnapsack.insertItem(new Item(22, 12));
  myKnapsack.insertItem(new Item(55, 56));
  myKnapsack.insertItem(new Item(12, 3));
  myKnapsack.insertItem(new Item(55, 6));
  myKnapsack.insertItem(new Item(15, 10));
	
  myKnapsack.findSolution();
  console.log(myKnapsack.reportSolution()); //Writes item0:(wt:23, val:34) item3:(wt:55, val:56) 
                                            //       item6:(wt:15, val:10) total:(wt:93, val:100)					
					
Get solution
Challenge 1

Assume that you have the following HTML:

  <div class="stopwatch">
    <form>
      <div id="stopwatch1">00:00:00.0</div>
      <input type="button" value="Start" id="start-stopwatch1">
    </form>
  </div>
						

Write a program that does the following:

  • When a visitor clicks the start button, the stopwatch starts running. The writing on the button changes to Stop.
  • When a visitor clicks the stop button, the stopwatch stops. The writing on the button changes to Reset.
  • When a visitor clicks the reset button, the stopwatch resets to zero. The writing on the button changes back to Start.

Hint: To format the time, you can use the solution of Challenge 1, Meeting 8.

Get solution
Challenge 1

Write a program that will allow you to play a classic memory board game like the one below.

Icons made by Freepik from www.flaticon.com licensed by CC BY 3.0
Get solution
Challenge 1

Write a recursive function that returns the nth Fibonacci number (see Meeting 9, Challenge 1).

Explanation: Certain types of problems can be broken down into smaller subproblems of the same type, which can be further broken down into even smaller subproblems. Eventually, you arrive at a subproblem simple enough to be solved directly. This process of breaking down a problem into smaller and smaller subproblems of the same type is called recursion. Recursive problems can be represented by a tree and implemented as a function calling itself.

For example, a process of recursively computing the fifth Fibonacci number can be summarized in the following tree.

Notice how the main problem of computing the fifth Fibonacci number is decomposed into the subproblems of computing the fourth and third Fibonacci numbers. The subproblem of computing the fourth Fibonacci number is further decomposed into the subproblems of computing the third and second Fibonacci numbers. Finally, the subproblem of computing the third Fibonacci number is the most basic one and can be solved directly by summing the first and second numbers which are specified by definition.

Get solution
Challenge 2

Recursion is not very efficient since it consumes memory and time resources, and the problem of finding Fibonacci numbers is much more efficient when it is implemented iteratively as, for example, is the solution presented in Meeting 9, Challenge 1. That said, you will be sometimes prepared to sacrifice some efficiency for a more elegant and understandable solution, especially when you encounter a complex problem that is recursive by nature, like, for example, the following programming challenge.

Using the Box class from Meeting 11, Challenge 1, write a program that, given an array of boxes, finds the longest series of boxes that can be put one into the other so that the largest box of the found series contains all the other boxes, the second largest contains all but the largest box, and so forth.

The problem can be solved by trying out all the possible combinations of given boxes. Since a larger box cannot be placed into a smaller one, you can first sort the boxes by volume. Then, starting with the smallest box, you try to put the box into the second smallest box. If it doesn't fit, you try the next one, and so forth, until you either find a box that the first box fits into or you repeat the whole process with the second smallest box. Every time you get to the largest box, you count the number of boxes that you succeeded to put one into the other.

Hint: Before you start to write a program, draw a tree that depicts the process of trying to put boxes into the other boxes.

Get solution
Furter Reading

If you have been intrigued by recursion, I suggest that you read the chapter on recursion from the Design and Implementation of Computer Applications Course Notes by Mathieu Couture. Note that the examples are written in Java (which is not JavaScript) but I think that you shouldn't have any troubles with understanding the code.

Challenge 1

Extend the Sudoku application from the book (finished in Appendix A) so that it will remember a partial solution entered by a player even when he/she leaves the page and returns back later. Use the Web Storage to implement the needed data storage. Also, add a "new" button that will clear the grid and generate a new Sudoku puzzle.

Hint: You can store the puzzle state to local memory just before the page unloads, which triggers the unload event on the window object. You might also want to rewrite certain parts of the existing code in order to easier implement the required additions. In practice, it is sometimes necessary to do so at certain stages of a project, when you discover that you overlooked certain details or—even more likely—not all the knowledge needed was available at the planning stage.

Note: The Web Storage is not available locally in IE, so you will have to upload your code to a web server if you want to test it in IE.

Get solution

You can download a zip file containing the source code of the examples from the book. Each file is named by a page number where the example starts and a short title of the example. There is a separate folder for each meeting containing all the necessary files.

Notes:

  1. You can run the examples locally, except for the Ajax example from Appendix B, which you need to upload to a web server in order to be able to run it.
  2. If you are using IE, you will have to upload to a web server the Memo example as well, as the Web Storage is not available locally in IE.
  3. Some examples write text to the JavaScript Console and you will see nothing when you load them unless you open the Console.