-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path10126.go
91 lines (82 loc) · 1.55 KB
/
10126.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// UVa 10126 - Zipf's Law
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strings"
)
func isAlphabet(b byte) bool { return b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' }
func parse(line string) []string {
var b byte
var word string
var words []string
for r := strings.NewReader(line); ; {
if _, err := fmt.Fscanf(r, "%c", &b); err != nil {
if word != "" {
words = append(words, word)
}
break
}
if !isAlphabet(b) {
if word != "" {
words = append(words, word)
word = ""
}
} else {
word += string(b)
}
}
return words
}
func count(words []string) map[string]int {
m := make(map[string]int)
for _, word := range words {
m[strings.ToLower(word)]++
}
return m
}
func get(frequency map[string]int, n int) []string {
var words []string
for k, v := range frequency {
if v == n {
words = append(words, k)
}
}
sort.Strings(words)
return words
}
func main() {
in, _ := os.Open("10126.in")
defer in.Close()
out, _ := os.Create("10126.out")
defer out.Close()
s := bufio.NewScanner(in)
s.Split(bufio.ScanLines)
var n int
var line string
first := true
for s.Scan() {
fmt.Sscanf(s.Text(), "%d", &n)
frequency := make(map[string]int)
for s.Scan() {
if line = s.Text(); line == "EndOfText" {
break
}
for k, v := range count(parse(line)) {
frequency[k] += v
}
}
if first {
first = false
} else {
fmt.Fprintln(out)
}
if words := get(frequency, n); len(words) > 0 {
fmt.Fprintln(out, strings.Join(words, "\n"))
} else {
fmt.Fprintln(out, "There is no such word.")
}
}
}