Full-Stack course / JavaScript fundamentals
Collatz chain
How to fetch and submit this exercise
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach exercise: download it, edit the file named in the instructions, then submit.
gonomicon fetch fs-week-2/01-07-collatz-chain
cd 01-07-collatz-chain
gonomicon submitCollatz chain
Goal: follow the 3n+1 chain from a starting number down to 1, counting the moves and writing down every number you visit.
The rule
Start with any positive whole number. Make a move:
- if the current number is even, halve it
- if it is odd, triple it and add 1
Keep making moves until you reach 1. (Nobody has ever found a starting number that doesn't get there, but nobody has proved it either.)
Worked example
Starting at 6:
| Move | Current number | Even or odd? | Next number |
|---|---|---|---|
| 1 | 6 | even | 3 |
| 2 | 3 | odd | 10 |
| 3 | 10 | even | 5 |
| 4 | 5 | odd | 16 |
| 5 | 16 | even | 8 |
| 6 | 8 | even | 4 |
| 7 | 4 | even | 2 |
| 8 | 2 | even | 1 |
So steps is 8 and path is "6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1": every number visited, starting number and final 1 included, with -> between them.
If start is 1, you're already there: steps is 0 and path is "1".
Rules
- Keep the line
let start = ...;at the top of the file. The tests replace the number on it. It is always a positive whole number. - Declare
const steps(a number) andconst path(a string). - Follow the chain with a
whileloop. - Some chains climb a long way before they fall.
27takes 111 moves and goes above 9000, and starting numbers near a million must still finish quickly. - Don't use
var, and don't use loose==or!=. - To look at your boxes while you work, add
console.log(steps, path);at the bottom and runnode collatz_chain.js.
What you'll practice
- A
whileloop that runs until a condition says stop - Choosing a track with
ifandelseon every lap - Keeping several
letboxes in step with each other - Building text with a template literal, one piece per lap
- Copying results into
constboxes once the work is done
Run it
gonomicon fetch fs-week-2/01-07-collatz-chain
cd 01-07-collatz-chain
gonomicon test
gonomicon submit
Hints
- You don't know how many moves it will take, only when to stop: when the number reaches 1. That's a job for
while. Keep the number you're working on in its ownletbox, sostartstays as it was. - Before the loop, make three
letboxes: the current number, a move counter at 0, and a text box that begins with the starting number. Each lap: decide even or odd with% 2, change the current number, add 1 to the counter, and add->plus the new number to the text. while (current !== 1) { if (current % 2 === 0) { current = current / 2; } else { current = current * 3 + 1; } count++; trail +=-> ${current}; }. After the loop, put the results into the boxes the tests look at:const steps = count;andconst path = trail;.