-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajority-element-go.go
More file actions
53 lines (45 loc) · 928 Bytes
/
majority-element-go.go
File metadata and controls
53 lines (45 loc) · 928 Bytes
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
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"strings"
)
func parseFile(filename string) []string {
line_bytes, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
line := string(line_bytes)
clean_line := strings.Trim(line, "\n")
return strings.Split(clean_line, ",")
}
func getCounts(elements []string) map[string]int {
counts := make(map[string]int)
for _, element := range elements {
_, present := counts[element]
if present {
counts[element]++
} else {
counts[element] = 1
}
}
return counts
}
func naiveMajorityElement(elements []string) {
counts := getCounts(elements)
for k, v := range counts {
if v > len(elements) / 2 {
fmt.Println(k)
return
}
}
fmt.Println(nil)
}
var inputFile = flag.String("input-file", "input.txt", "input file")
func main() {
flag.Parse()
elements := parseFile(*inputFile)
naiveMajorityElement(elements)
}