Lesson 1.2
Say it in your own words
6 min · 7 steps
Step 1 of 7 · Explanation
Before coding, restate the problem in one sentence: what goes in, what comes out, what the rule is.
Problem: "Return how many days were warmer than the day before."
Your version: "Count eachiwheretemps[i] > temps[i - 1], starting ati = 1."The second sentence is almost code already. Then work one example by hand. For
[20, 22, 21, 25], 22 is warmer than 20 and 25 is warmer than 21, so the answer is 2.Step 2 of 7 · Pick the approach
Problem: "Return how many days were warmer than the day before."
Which restatement is right?- Count each
iwithtemps[i] > temps[i - 1], starting ati = 1 - Count the days warmer than the first day
- Count each
iwithtemps[i] > temps[i - 1], starting ati = 0 - Return the biggest rise in temperature
- Count each
Step 3 of 7 · Predict the result
Work it by hand. What does it return for
[20, 22, 22, 21, 25]?function solution(temps) { let count = 0 for (let i = 1; i < temps.length; i++) { if (temps[i] > temps[i - 1]) count++ } return count}234
Step 4 of 7 · Trace the code
For
temps = [5, 8, 3], fill iniandcountat each marked step.function solution(temps) { let count = 0 for (let i = 1; i < temps.length; i++) { if (temps[i] > temps[i - 1]) count++ } return count}solution([5, 8, 3])
Step 5 of 7 · Explanation
The examples in the problem are rarely enough. Make your own small example, then write the output you expect before running the code.
The most useful one is usually the smallest that still makes sense: one item, or two equal items.
Step 6 of 7 · Predict the result
Your own example, just one day. What does it return for
[7]?function solution(temps) { let count = 0 for (let i = 1; i < temps.length; i++) { if (temps[i] > temps[i - 1]) count++ } return count}017
Step 7 of 7 · Recap
- Restate the problem in one sentence with the input, the rule, and the output.
- Work the examples by hand. Write down every pair being compared.
- Make your own small example and write its result before running the code.