From Zero to Senior · The LabالعربيةGitHub

Chapter 2

Thinking in Steps: Algorithms

3 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • explain what an algorithm is, and what makes a good one
  • break a big problem into small, clear steps
  • write your plan as pseudocode and draw it as a flowchart
  • recognise the three building blocks of every program
  • test an algorithm by hand before you write any code

Examples

2.5 The three building blocks

A simple program that uses only sequence looks like this. It works out the average of three test scores:

average.js⤓ File
// Sequence: each step runs once, in order.
const first = 8;
const second = 6;
const third = 10;

const total = first + second + third;
const average = total / 3;

console.log(`Average: ${average}`);
Recorded output$ node average.js
Average: 8

2.6 From pseudocode to JavaScript

Now the exciting part. Look at the pseudocode from Section 2.3 again, and then at the same algorithm written in JavaScript:

largest.js⤓ File
const cards = [7, 3, 12, 5, 9];
let largest = cards[0];

for (const card of cards) {
  if (card > largest) {
    largest = card;
  }
}

console.log(`The largest card is ${largest}`);
Recorded output$ node largest.js
The largest card is 12

2.8 A taste of efficiency

Method 2: open the book in the middle. If “Omar” comes before that page, throw away the second half; otherwise throw away the first half. Repeat with the half that is left. Each step halves the problem. How many steps does it take? Let the computer count:

halving.js⤓ File
let names = 1000000;
let steps = 0;

while (names > 1) {
  names = Math.ceil(names / 2);
  steps = steps + 1;
}

console.log(`Steps needed: ${steps}`);
Recorded output$ node halving.js
Steps needed: 20

Practice projects

Project 2.1 · Easy

The cheapest product

A shopper wants the cheapest item in a list of prices. Plan the algorithm, test it by hand, then turn it into JavaScript.

You will practise: decomposition, pseudocode, trace tables, and translating a plan into code.

Steps
  1. Write the pseudocode. Start from the largest-card algorithm in Section 2.3: what is the one word you need to change?
  2. Make a trace table for the prices 42, 18, 35, 9 and 27, with the columns “price”, “price < cheapest?” and “cheapest”.
  3. Copy largest.js from Section 2.6 into a new file, cheapest.js, and change it to follow your pseudocode. Rename the variables so that they say what they mean.
  4. Run it, and compare the answer with the last line of your trace table.

Hint: only the comparison changes: < instead of >. Good names, like cheapest instead of largest, make the code tell the truth.

Solution
cheapest.js⤓ File
const prices = [42, 18, 35, 9, 27];
let cheapest = prices[0];

for (const price of prices) {
  if (price < cheapest) {
    cheapest = price;
  }
}

console.log(`The cheapest price is ${cheapest}`);
Recorded output$ node cheapest.js
The cheapest price is 9

Project 2.2 · Medium

Guess my number

A friend thinks of a number from 1 to 100 and answers only “too high” or “too low”. Write the strategy that always wins in at most seven guesses, and let the computer play it.

You will practise: binary search, keeping track of a range, and repetition.

Steps
  1. Play the game with a friend, on paper. Always guess the middle of the numbers that are still possible. Write down each guess.
  2. Write the strategy as pseudocode with two values, LOW and HIGH. What happens to them after “too low”? After “too high”?
  3. Type the solution below into guess.js. It uses a while loop and break, which you will learn properly in Chapter 9; for now, follow the shape: repeat: guess the middle; if right, stop; otherwise move LOW or HIGH.
  4. Change secret to other numbers, such as 1, 100 and 64. Does it ever need more than seven guesses?

Hint: Math.floor rounds down, so the middle of 1 and 100 is 50, not 50.5. Seven guesses are always enough because 27 = 128, which is more than 100.

Solution
guess.js⤓ File
const secret = 73;
let low = 1;
let high = 100;
let tries = 0;

while (true) {
  const guess = Math.floor((low + high) / 2);
  tries++;
  if (guess === secret) {
    console.log(`Guess ${tries}: ${guess}. Got it!`);
    break;
  }
  if (guess < secret) {
    console.log(`Guess ${tries}: ${guess}, too low`);
    low = guess + 1;
  } else {
    console.log(`Guess ${tries}: ${guess}, too high`);
    high = guess - 1;
  }
}
Recorded output$ node guess.js
Guess 1: 50, too low
Guess 2: 75, too high
Guess 3: 62, too low
Guess 4: 68, too low
Guess 5: 71, too low
Guess 6: 73. Got it!

Project 2.3 · Challenge

Sort three cards

Put three numbers in order from smallest to largest, using only comparisons and swaps, the way a sorting machine does.

You will practise: designing an algorithm, testing every case, and thinking about correctness.

Steps
  1. Take three cards and sort them by hand, only ever comparing two neighbours and swapping them if they are in the wrong order. How many comparisons do you need?
  2. Write the steps as pseudocode: “if A > B, swap A and B”, and so on.
  3. Test your algorithm by hand on all six possible orders of 1, 2 and 3. A correct algorithm must sort every one of them.
  4. Write it in JavaScript. A neat way to swap two variables is [a, b] = [b, a];.

Hint: compare A with B, then B with C (now the largest is at the end), then A with B again. Three comparisons are enough for three numbers.

Solution
sort-three.js⤓ File
let a = 12;
let b = 3;
let c = 7;

// Three comparisons are enough to sort three numbers
if (a > b) [a, b] = [b, a];
if (b > c) [b, c] = [c, b];
if (a > b) [a, b] = [b, a];

console.log(a, b, c);
Recorded output$ node sort-three.js
3 7 12

Exercises

Exercise 2.1 · Easy

Write pseudocode for finding the smallest card. What do you need to change from the largest-card algorithm?
The book's short answer
The same algorithm with “smaller than” instead of “bigger than”, and a variable called SMALLEST.
Show the solution

Pseudocode: the smallest card

SET SMALLEST to the first card
FOR EACH CARD in the pile
    IF CARD is smaller than SMALLEST
        SET SMALLEST to CARD
SHOW SMALLEST

Only two things change from the largest-card algorithm: "bigger than" becomes "smaller than", and the variable gets an honest name, SMALLEST.

smallest.js is the same algorithm in JavaScript, with a trace of every step.

smallest.js⤓ File
const cards = [7, 3, 12, 5, 9];
let smallest = cards[0];

for (const card of cards) {
  if (card < smallest) {
    smallest = card;
  }
  console.log(`Card ${card} -> smallest so far ${smallest}`);
}

console.log(`The smallest card is ${smallest}`);
Recorded output$ node smallest.js
Card 7 -> smallest so far 7
Card 3 -> smallest so far 3
Card 12 -> smallest so far 3
Card 5 -> smallest so far 3
Card 9 -> smallest so far 3
The smallest card is 3

Exercise 2.2 · Easy

Draw a flowchart for crossing a road at traffic lights.
The book's short answer
Start → Is the light green for pedestrians? → no: wait and ask again; yes: look both ways → Is the road clear? → no: wait; yes: cross → End.
Show the solution

Flowchart: crossing a road at traffic lights

flowchart TD
    A([Start]) --> B{Is the pedestrian light green?}
    B -- No --> W1[Wait] --> B
    B -- Yes --> L[Look left and right]
    L --> C{Is the road clear?}
    C -- No --> W2[Wait] --> C
    C -- Yes --> X[Cross]
    X --> E([End])

The two "Wait" boxes are loops: the arrow goes back to the question, so the question is asked again and again until the answer changes. crossing.js follows the same flowchart for one walker.

crossing.js⤓ File
// What the walker sees each second: the light, and whether a car is coming.
const seconds = [
  { light: "red", car: false },
  { light: "red", car: true },
  { light: "green", car: true },
  { light: "green", car: false },
];

console.log("Start");
for (const now of seconds) {
  if (now.light !== "green") {
    console.log("The light is red: wait");
  } else if (now.car) {
    console.log("Green, but a car is coming: wait");
  } else {
    console.log("Green and the road is clear: cross");
    break;
  }
}
console.log("End");
Recorded output$ node crossing.js
Start
The light is red: wait
The light is red: wait
Green, but a car is coming: wait
Green and the road is clear: cross
End

Exercise 2.3 · Medium

Write pseudocode that counts how many cards are bigger than 5. Trace it with the cards 7, 3, 12, 5, 9. (The answer should be 3.)
The book's short answer
Set COUNT to 0; for each CARD, if CARD is bigger than 5, add 1 to COUNT; show COUNT. The trace gives 1 (7), 1, 2 (12), 2, 3 (9).
Show the solution

Pseudocode: how many cards are bigger than 5?

SET COUNT to 0
FOR EACH CARD in the pile
    IF CARD is bigger than 5
        ADD 1 to COUNT
SHOW COUNT
Card Bigger than 5? COUNT
7 yes 1
3 no 1
12 yes 2
5 no (5 is not bigger than 5) 2
9 yes 3

Answer: 3. count-bigger.js prints the same trace.

count-bigger.js⤓ File
const cards = [7, 3, 12, 5, 9];
let count = 0;

for (const card of cards) {
  if (card > 5) {
    count = count + 1;
  }
  console.log(`Card ${card} -> count ${count}`);
}

console.log(`Cards bigger than 5: ${count}`);
Recorded output$ node count-bigger.js
Card 7 -> count 1
Card 3 -> count 1
Card 12 -> count 2
Card 5 -> count 2
Card 9 -> count 3
Cards bigger than 5: 3

Exercise 2.4 · Medium

Using binary search, how many steps do you need for 1,000 names? Change halving.js to check your answer.
The book's short answer
10 steps for 1,000 names, because 210 = 1,024.
Show the solution
halving-1000.js⤓ File
// halving.js from the chapter, with 1,000 names instead of 1,000,000.
let names = 1000;
let steps = 0;

while (names > 1) {
  names = Math.ceil(names / 2);
  steps = steps + 1;
}

console.log(`Steps needed: ${steps}`);

// Why 10? Because 2 multiplied by itself 10 times is 1,024, the first power of 2 above 1,000.
console.log(2 ** 9, 2 ** 10);

// The same question for other list sizes: doubling the list adds only one step.
for (const size of [10, 100, 1000, 2000, 1000000]) {
  let left = size;
  let n = 0;
  while (left > 1) {
    left = Math.ceil(left / 2);
    n = n + 1;
  }
  console.log(`${size} -> ${n}`);
}
Recorded output$ node halving-1000.js
Steps needed: 10
512 1024
10 -> 4
100 -> 7
1000 -> 10
2000 -> 11
1000000 -> 20

Exercise 2.5 · Challenge

Write pseudocode that finds both the largest and the second-largest card in one pass through the pile. Trace it with 7, 3, 12, 5, 9, and then with 12, 12, 4.
The book's short answer
Keep LARGEST and SECOND. For each card: if it is bigger than LARGEST, SECOND becomes LARGEST and LARGEST becomes the card; otherwise, if it is bigger than SECOND, SECOND becomes the card. For 7, 3, 12, 5, 9 you get 12 and 9. For 12, 12, 4 you get 12 and 12 (or 12 and 4, if you decide that the second-largest must be different; decide and say so).
Show the solution

Pseudocode: the largest and the second-largest, in one pass

SET LARGEST to nothing, SECOND to nothing
FOR EACH CARD in the pile
    IF there is no LARGEST, or CARD is bigger than LARGEST
        SET SECOND to LARGEST
        SET LARGEST to CARD
    OTHERWISE IF there is no SECOND, or CARD is bigger than SECOND
        SET SECOND to CARD
SHOW LARGEST and SECOND

Trace with 7, 3, 12, 5, 9:

Card LARGEST SECOND
7 7 —
3 7 3
12 12 7
5 12 7
9 12 9

With 12, 12, 4 this algorithm gives 12 and 12: the second 12 is not bigger than LARGEST, but it is bigger than SECOND (nothing). If you decide the second-largest must be a different value, add "and CARD is not equal to LARGEST" to the second test, and you get 12 and 4. Both are correct, as long as you decide and say so. top-two.js runs both versions.

top-two.js⤓ File
function topTwo(cards, distinct) {
  let largest = null;
  let second = null;
  for (const card of cards) {
    if (largest === null || card > largest) {
      second = largest;
      largest = card;
    } else if ((second === null || card > second) && !(distinct && card === largest)) {
      second = card;
    }
    console.log(`  ${card} -> ${largest}, ${second ?? "—"}`);
  }
  return [largest, second];
}

console.log("7, 3, 12, 5, 9:");
console.log(`Largest and second: ${topTwo([7, 3, 12, 5, 9], false).join(" and ")}`);

console.log("12, 12, 4:");
console.log(`Allowing equal values: ${topTwo([12, 12, 4], false).join(" and ")}`);

console.log("12, 12, 4:");
console.log(`Different values only: ${topTwo([12, 12, 4], true).join(" and ")}`);
Recorded output$ node top-two.js
7, 3, 12, 5, 9:
  7 -> 7, —
  3 -> 7, 3
  12 -> 12, 7
  5 -> 12, 7
  9 -> 12, 9
Largest and second: 12 and 9
12, 12, 4:
  12 -> 12, —
  12 -> 12, 12
  4 -> 12, 12
Allowing equal values: 12 and 12
12, 12, 4:
  12 -> 12, —
  12 -> 12, —
  4 -> 12, 4
Different values only: 12 and 4