Start learning free

LESSON 238 OF 671 · SETS

Removing from a Set and Looping Over It in Go

Lesson

TL ; DR:

delete(s, x) takes x out of a map used as a set. A for loop with range visits every key once, in no fixed order.


colors := map[string]bool{"red": true, "blue": true, "green": true}

delete(colors, "blue")
delete(colors, "pink")          // not in it, nothing happens

for color := range colors {
    fmt.Println(color)          // red and green, in any order
}


Full lesson:

In Go, a set is a map with bool values. delete(s, x) removes the key x from it. If x isn't there, nothing happens.

for x := range s visits each key of the map once. With one variable, range gives only the keys. That's all a set needs.

The order isn't fixed. Go even picks a different order on purpose, from one run to the next.

So loop over a set when the order doesn't matter. A total, a count and a check are fine.


Your task

In a word game, the set found holds the words a player found. The words "qqq" and "zzz" aren't allowed. Remove both from found.

The player never found "zzz", so removing it changes nothing.

Then add up the points. A word scores one point per letter. Loop over found and add each word's length to score.

The code already prints how many words are left, and the points.

Expected output:

4 words
14 points
STEP 1 OF 3
    Ctrl + Enter to check