Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

# How to count the total number of letters concurrently in Golang

Jeyabalaji Subramanian

### Problem statement

Write a concurrent Golang program to count the total number of letters in a given paragraph.

### Solution approach

As we outlined in the previous chapter, the first thing to tackle in the solution is to identify the core function that we would like to run concurrently.

Now, let’s write this core functioncount letters in a word as a goroutine.

package main

import (
"fmt"
"unicode/utf8"
)

func countLetters(s string, c chan int) {
c <- utf8.RuneCountInString(s)
}

func main() {
ch := make(chan int)

word1 := "Hola"
word2 := "Dias"

go countLetters(word1, ch)
letterCount1 := <-ch

go countLetters(word2, ch)
letterCount2 := <-ch

fmt.Println("Total letters in", word1, letterCount1, word2, letterCount2)
}


If you observe the above code closely, you can see anatomy of a loop. So, to complete the solution, we need to do the following:

• Given a paragraph, break this paragraph into a set of words.
• Get the word count concurrently and aggregate results into a total count.

Let’s take a look at the final solution in the below code:

package main

import (
"fmt"
"strings"
"time"
"unicode/utf8"
)

func countLetters(s string, c chan int) {
c <- utf8.RuneCountInString(s)
}

func main() {
ch := make(chan int)
totalCount := 0
start := time.Now()

fmt.Println("start", start)
myParagraph := "All the world is a stage"
myParagraphs := ""
for i := 0; i < 1000; i++ {
myParagraphs += " " + myParagraph
}

words := strings.Fields(myParagraphs)
for _, word := range words {
go countLetters(word, ch)
totalCount += <-ch
}

fmt.Println("Total letters: ", totalCount)
fmt.Println("end", time.Since(start))
}

In the above example,

• For each word, a goroutine is initiated to count letters.
• The receiver accumulates the count into totalCount variable.

RELATED TAGS

golang
communitycreator

CONTRIBUTOR

Jeyabalaji Subramanian
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.