Course outline
Course / The terminal and the language

Fill in the form letter

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/09-05-build-the-summary
cd 09-05-build-the-summary
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 two functions that build text with fmt.Sprintf: Summary reports an average with two decimals, and Badge reports how many symbols and bytes a name has.

Example

Name, Total, Count = "Ada", 10, 3
fmt.Println(Summary()) // Ada: 3 items, average 3.33
fmt.Println(Badge())   // "Ada" (3 symbols, 3 bytes)

Name = "héllo"
fmt.Println(Badge())   // "héllo" (5 symbols, 6 bytes)

10 divided by 3 is 3.333..., and %.2f rounds it to 3.33. In Badge, the name is wrapped in double quotes, and the symbol count and byte count differ for héllo.

Rules

  • Edit summary.go. Each function has a // TODO comment and a return line you will change.
  • Name, Total and Count are variables outside the functions. The tests give them different values, so read them each time the functions run.
  • Summary returns exactly <Name>: <Count> items, average <Total divided by Count, with 2 decimals>. The average must keep its decimals, so convert both numbers to float64 before dividing. Count is never zero.
  • Badge returns exactly <Name in double quotes> (<symbols> symbols, <bytes> bytes). Use %q for the quotes.
  • Build both results with fmt.Sprintf. You will need import "fmt" and import "unicode/utf8" at the top of the file.
  • Do not change the three var lines or the func lines.

What you'll practice

Filling a template with Sprintf verbs (%s, %d, %.2f, %q), converting between number types before dividing, and counting symbols against bytes.

Run it

gonomicon fetch week-1/09-05-build-the-summary
cd 09-05-build-the-summary
gonomicon test
gonomicon submit

Hints

  1. Sprintf builds the text from a template. %s fills in a string, %d a whole number, %.2f a decimal with two digits, and %q a string in double quotes.
  2. The average needs decimals, so convert both numbers first: float64(Total) / float64(Count). For Badge, count symbols with utf8.RuneCountInString(Name) and bytes with len(Name).
  3. Summary: fmt.Sprintf("%s: %d items, average %.2f", Name, Count, float64(Total)/float64(Count)). Badge: fmt.Sprintf("%q (%d symbols, %d bytes)", Name, utf8.RuneCountInString(Name), len(Name)).

Something wrong with this lesson? Report a problem