+100 XP
instructions11 / 63
taught in: control flow
Mediumcontrol-flowloopsslices~30m+100 XP
Loop Patterns
Go has one loop keyword. There is no while, no do, no foreach, and no
comprehension. for covers all of it by dropping clauses:
for i := 0; i < n; i++ { } // counter
for n != 1 { } // while
for { } // forever, until break
for i, v := range items { } // each element
break ends the innermost loop and continue skips to its next iteration. When
you need to leave an outer loop from inside an inner one, label it and say
which: break search. That label is not a goto; it names a loop, and it is
the readable alternative to a found flag threaded through two conditions.
range over a slice gives you index and value. Take only the index with
for i := range items, and drop the index with for _, v := range items. The
value is a copy, so assigning to v changes nothing.
Task
Finish the six functions in main.go. Each one is a different shape of loop.
SumTo(n int) intadds 1 throughnwith the three-clause form.nbelow 1 sums to0.CollatzSteps(n int) intcounts steps to reach 1: halve an even number, triple an odd one and add 1.CollatzSteps(1)is0,CollatzSteps(27)is111, and anything below 1 is-1.OddSquares(n int) []intreturns the squares of the odd numbers up ton, usingcontinueto skip the even ones.NextPowerOfTwo(n int) intreturns the smallest power of two at least as large asn, with aforthat has no clauses and abreak.FirstIndex(items []string, target string) intreturns the index of the first match, or-1, and stops as soon as it finds one.FindCell(grid [][]int, target int) (int, int)scans a grid row by row and returns the row and column of the first matching cell, or-1, -1. Rows may have different lengths, including zero.
Hints
- A
for i := 1; i <= n; i++never runs whennis0, so the "n below 1" cases need no extraif. Check that before writing one. - The Collatz loop needs its guard first:
n < 1returns-1before the loop, because the loop would otherwise never reach 1. continueruns the post statement on its way round, so the counter still advances. Acontinuein a condition-onlyforthat forgets to advance the variable itself is an infinite loop, and in the runner that is a timeout rather than an error message.- Appending to a
nilslice is fine, sovar out []intis a complete initialisation.OddSquares(0)then returnsnil, which has length zero and is what the tests expect. FirstIndexcan justreturn ifrom inside the range; that is abreakthat also hands back the answer.FindCellis the one that wants a label. Writesearch:on the line above the outerfor, thenbreak searchfrom the inner loop. Do it with a plainbreakinstead and the outer loop keeps going, which quietly returns the last match rather than the first.- Ranging over an empty or
nilslice runs the body zero times, so the empty row in the test grid needs no special case.