Course outline
Course / The terminal and the language

Find the first matching pair

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each 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 submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

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 = 1 with Limit of 1 or more gives "1,1".
  • A prime Target bigger than Limit has no pair, except the pair with 1 that fits inside the limit: Limit = 7, Target = 7 gives "1,7", but Limit = 5, Target = 7 gives "none".
  • If Limit is 0 or negative, nothing is searched and the answer is "none".

Rules

  • Edit pair.go. The function has a // TODO comment and a return line you will change.
  • Limit and Target are 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 i outside and j inside, both counting from 1 to Limit.
  • Keep a found flag (a bool declared before the loops) and stop both loops with break as soon as a pair is found. A break only leaves the loop it is written in, so the outer loop needs its own check of the flag.
  • Do not return from inside the loops: finish the loops, then return the result.
  • Do not change the lines var Limit int, var Target int or func FindPair() string {. Do not add imports other than fmt.

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

  1. Use two loops, i outside and j inside, both from 1 up to Limit. Check i*j == Target on every pass of the inner loop.
  2. Declare found := false and a result string before the loops. When you hit a match, store the pair, set found = true and break. A break only leaves the inner loop, so add if found { break } right after the inner loop in the outer one.
  3. Start with result := "none". When i*j == Target, set result = fmt.Sprintf("%d,%d", i, j), set found = true and break. After the inner loop, if found { break }. Return result after the loops.

Something wrong with this lesson? Report a problem