Problem Solving Fundamentals · Approaching a Problem

Trace a worked example

the worked example

Trace a worked example

Here is a small task: given a sentence, return how many words it holds. You could reach for code straight away, but first take one sentence and walk through it by hand.

"the quick brown fox"

How many words? Four. You did not count by magic. You looked at each word in turn and kept a running total: the is one, quick makes two, brown makes three, fox makes four.

Now write down what you did. You start at zero. You move through the words one at a time, adding one for each. When the words run out, the total is your answer. That is the whole method, and you found it by hand before writing a line.

The trace exposes details a vague plan hides. It forces you to decide where the count starts — zero, not one — and when to stop — after the last word. Those are exactly the places code goes wrong.

Try the empty sentence, "". You start at zero, there are no words to visit, and you stop. The answer is zero. You did not guess what an empty sentence should return; the example told you.

Only now does the code fall out. You have a start value, a step, and a stop condition, each checked against real input:

function wordCount(sentence) {
  return sentence.split(' ').filter(Boolean).length;
}

The code is the least interesting part. The work was the sentence you traced and the rules it handed you.

You are about to answer a short quiz on tracing a worked example.

  1. Tracing one concrete input by hand can reveal details a vague plan hides.
  2. Walking through a single input step by step before writing code is called tracing a worked ___.
  3. A worked example is only useful once the code is already written.
  4. Tracing the empty sentence tells you what the function should return for the ___ input.
  5. A worked example decides where a running total starts and when the loop stops.