Course / The terminal and the language
Find the first matching pair
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach lab: download it, edit the file named in the instructions, then submit.
gonomicon fetch week-1/11-08-first-matching-pair
cd 11-08-first-matching-pair
gonomicon submitGoal
Fill in FindPair so it searches every pair i, j from 1 to Limit and returns the first pair whose product equals Target, written as "i,j", or "none" if there is no such pair.
Example
Limit = 5
Target = 6
fmt.Println(FindPair()) // 2,3
Target = 7
fmt.Println(FindPair()) // none
Pairs are checked in row-major order: i is the row (outer loop) and j is the column (inner loop), so 1,1 1,2 1,3 ... then 2,1 2,2 ... With Limit = 6 and Target = 6, both 1,6 and 2,3 match, and 1,6 wins because it comes first.
Target = 1withLimitof 1 or more gives"1,1".- A prime
Targetbigger thanLimithas no pair, except the pair with 1 that fits inside the limit:Limit = 7,Target = 7gives"1,7", butLimit = 5,Target = 7gives"none". - If
Limitis 0 or negative, nothing is searched and the answer is"none".
Rules
- Edit
pair.go. The function has a// TODOcomment and areturnline you will change. LimitandTargetare variables outside the function. The tests give them different values, so read them each time the function runs.- Use one loop nested inside another, with
ioutside andjinside, both counting from 1 toLimit. - Keep a
foundflag (abooldeclared before the loops) and stop both loops withbreakas soon as a pair is found. Abreakonly leaves the loop it is written in, so the outer loop needs its own check of the flag. - Do not
returnfrom inside the loops: finish the loops, then return the result. - Do not change the lines
var Limit int,var Target intorfunc FindPair() string {. Do not add imports other thanfmt.
What you'll practice
Nested loops, stopping both loops with break and a flag, and building a result with fmt.Sprintf.
Run it
gonomicon fetch week-1/11-08-first-matching-pair
cd 11-08-first-matching-pair
gonomicon test
gonomicon submit
Hints
- Use two loops,
ioutside andjinside, both from 1 up toLimit. Checki*j == Targeton every pass of the inner loop. - Declare
found := falseand a result string before the loops. When you hit a match, store the pair, setfound = trueandbreak. Abreakonly leaves the inner loop, so addif found { break }right after the inner loop in the outer one. - Start with
result := "none". Wheni*j == Target, setresult = fmt.Sprintf("%d,%d", i, j), setfound = trueandbreak. After the inner loop,if found { break }. Returnresultafter the loops.