Skip to content

Commit a4e8269

Browse files
author
Nasseredine Bajwa
committed
Add solution for Challenge 6 by nasseredine
1 parent a78ee93 commit a4e8269

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Package challenge6 contains the solution for Challenge 6.
2+
package challenge6
3+
4+
import (
5+
"strings"
6+
"unicode"
7+
)
8+
9+
// CountWordFrequency takes a string containing multiple words and returns
10+
// a map where each key is a word and the value is the number of times that
11+
// word appears in the string. The comparison is case-insensitive.
12+
//
13+
// Words are defined as sequences of letters and digits.
14+
// All words are converted to lowercase before counting.
15+
// All punctuation, spaces, and other non-alphanumeric characters are ignored.
16+
//
17+
// For example:
18+
// Input: "The quick brown fox jumps over the lazy dog."
19+
// Output: map[string]int{"the": 2, "quick": 1, "brown": 1, "fox": 1, "jumps": 1, "over": 1, "lazy": 1, "dog": 1}
20+
func CountWordFrequency(text string) map[string]int {
21+
wordFrequency := make(map[string]int)
22+
23+
var token strings.Builder
24+
for _, r := range text {
25+
if unicode.IsLetter(r) || unicode.IsDigit(r) {
26+
token.WriteRune(unicode.ToLower(r))
27+
} else if r != '\'' {
28+
if token.Len() > 0 {
29+
flushToken(wordFrequency, &token)
30+
}
31+
}
32+
}
33+
if token.Len() > 0 {
34+
flushToken(wordFrequency, &token)
35+
}
36+
37+
return wordFrequency
38+
}
39+
40+
func flushToken(wordFrequency map[string]int, token *strings.Builder) {
41+
wordFrequency[token.String()]++
42+
token.Reset()
43+
}

0 commit comments

Comments
 (0)