Golang. Exercise: Maps


So, there we have exercise 23 from Go Tour.

Implement the WordCount function. It should return a map (data type map) of the counts of each “word” in the string s. The function wc.Test runs a set of tests against the provided function and outputs success or failure. It makes sense to use the strings.Fields function to perform the task.

Solution:

Let’s start by describing an approximate algorithm for what to do.

1) take sentence (string) and divide it to words with strings.Fields..
..it will return slice of substring
2) save each element of slice (array element) to map
3) if upon saving there is already the same named map element – do not add it, but increase number of duplicate element

What func Fields(s string) []string
Fields splits the string s around each instance of one or more consecutive space characters, as defined by unicode.IsSpace, returning a substring fragment of s or an empty fragment if s contains only a space.

Examples of strings to check:
I am learning Go!
I ate a donut. Then I ate another donut.

Code:

package main

import (
	"golang.org/x/tour/wc"
	"strings"
	//"fmt"
)

func WordCount(s string) map[string]int {
	
	var slice[] string
	slice = strings.Fields(s)	 
	// fmt.Printf("%q\n", slice)
	
	m := make(map[string]int)
	// fmt.Println (m)

	for _, value := range slice {
		m[value] += 1
	}
	
	return m
}

func main() {
	wc.Test(WordCount)
}

This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.