Skip to content

Commit 9ac78f8

Browse files
committed
Add solution for Challenge 6 by mick4711
1 parent f2745b3 commit 9ac78f8

File tree

2 files changed

+46
-10
lines changed

2 files changed

+46
-10
lines changed

challenge-6/solution-template.go

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,9 @@
22
package challenge6
33

44
import (
5-
"bytes"
5+
// Add any necessary imports here
66
)
77

8-
// Add any necessary imports here
9-
108
// CountWordFrequency takes a string containing multiple words and returns
119
// a map where each key is a word and the value is the number of times that
1210
// word appears in the string. The comparison is case-insensitive.
@@ -20,10 +18,5 @@ import (
2018
// Output: map[string]int{"the": 2, "quick": 1, "brown": 1, "fox": 1, "jumps": 1, "over": 1, "lazy": 1, "dog": 1}
2119
func CountWordFrequency(text string) map[string]int {
2220
// Your implementation here
23-
words := bytes.Fields([]byte(text))
24-
counts := make(map[string]int, len(words))
25-
for _, word := range words {
26-
counts[string(bytes.ToLower(word))]++
27-
}
28-
return counts
29-
}
21+
return nil
22+
}
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+
"bytes"
6+
"strings"
7+
"unicode"
8+
)
9+
10+
// CountWordFrequency takes a string containing multiple words and returns
11+
// a map where each key is a word and the value is the number of times that
12+
// word appears in the string. The comparison is case-insensitive.
13+
//
14+
// Words are defined as sequences of letters and digits.
15+
// All words are converted to lowercase before counting.
16+
// All punctuation, spaces, and other non-alphanumeric characters are ignored.
17+
//
18+
// For example:
19+
// Input: "The quick brown fox jumps over the lazy dog."
20+
// Output: map[string]int{"the": 2, "quick": 1, "brown": 1, "fox": 1, "jumps": 1, "over": 1, "lazy": 1, "dog": 1}
21+
func CountWordFrequency(text string) map[string]int { // Your implementation here
22+
// use whitespace and dash to parse out words
23+
f := func(c rune) bool {
24+
return unicode.IsSpace(c) || c == '-'
25+
}
26+
words := bytes.FieldsFunc([]byte(text), f)
27+
28+
// initialise return map
29+
counts := make(map[string]int, len(words))
30+
31+
// iterate through words filtering out invalid chars
32+
for _, word := range words {
33+
var b strings.Builder
34+
word = bytes.ToLower(word)
35+
for _, char := range word {
36+
if (char > 96 && char < 123) || (char > 47 && char < 58) {
37+
b.WriteByte(char)
38+
}
39+
}
40+
counts[b.String()]++
41+
}
42+
return counts
43+
}

0 commit comments

Comments
 (0)