-
Notifications
You must be signed in to change notification settings - Fork 0
/
day4.go
82 lines (69 loc) · 1.4 KB
/
day4.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
// http://adventofcode.com/2017/day/4
package main
import (
"os"
"bufio"
"fmt"
"strings"
"sort"
)
type RuneSlice []rune
func (r RuneSlice) Len() int { return len(r) }
func (r RuneSlice) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r RuneSlice) Less(i, j int) bool { return r[i] < r[j] }
func StringToRuneSlice(s string) []rune {
var r []rune
for _, runeValue := range s {
r = append(r, runeValue)
}
return r
}
func areAnagrams(s1, s2 string) bool {
var r1 RuneSlice = StringToRuneSlice(s1)
var r2 RuneSlice = StringToRuneSlice(s2)
sort.Sort(r1)
sort.Sort(r2)
return string(r1) == string(r2)
}
func isValidPassphrase1(s string) bool {
words := strings.Fields(s)
counts := make(map[string]int, len(words))
for _, word := range words {
counts[word]++
if counts[word] > 1 {
return false
}
}
return true
}
func isValidPassphrase2(s string) bool {
words := strings.Fields(s)
for i, word := range words {
for j := i+1; j < len(words); j++ {
if areAnagrams(word, words[j]) {
return false
}
}
}
return true
}
func main() {
counter1 := 0
counter2 := 0
f, err := os.Open("day4-input.txt")
if err != nil {
panic(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if isValidPassphrase1(scanner.Text()) {
counter1++
}
if isValidPassphrase2(scanner.Text()) {
counter2++
}
}
fmt.Println(counter1)
fmt.Println(counter2)
}