I am implementing a function that counts words and I am trying to write this with goroutines. So far I have made []string
arrays to suitable sizes of the original string text and I send these to a goroutine each to count the words and add them to k/v pair inside a map[string]int
, then I want to take them all through my channel and read all of the maps and simply count how many words in total there has been and return this map[string]int
, but this is where I am lost. I tried to do something like
mapSummary := make(map[string]int)
for k, v := range channel {
mapSummary[k] += v
}
but this does not work since I am using two variables in the range, and with only one I am not sure how to do this. So how do I add all of these maps together that I sent through a channel? I dont need you guys to show me exactly how this is done (it is a homework assignment) but since I did not recieve any help from my TAs in our labsession I would greatly appreciate some clues as to how this should be done, I also see that how I distribute the []string
array is not good, but that I will figure out myself! :) This code does not include the main function or a majority of the code, but the necessary parts that I hope help you understand it.
ch := make(chan map[string]int)
for i := 0; i < 8; i++ {
wg.Add(1)
words := text[i*(len(text)/8):(i+1)*(len(text)/8)]
go count(words, ch, wg)
}
wg.Wait()
mapSummary := make(map[string]int)
for k, v := range ch {
mapSummary[k] += v
}
return mapSummary
func count(words []string, ch chan<- map[string]int, wg *sync.WaitGroup) {
freqs := make(map[string]int)
for _, word := range words {
freqs[word] += 1
}
wg.Done()
ch <- freqs
}
it tells me "too many variables in range".