-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
116 lines (96 loc) · 1.79 KB
/
main.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"bufio"
"io"
"regexp"
"sort"
"strconv"
"strings"
)
var re = regexp.MustCompile(`^([a-z]+-)*(\d+)\[([a-z]+)\]$`)
func fs1(input io.Reader) (int, error) {
scanner := bufio.NewScanner(input)
sum := 0
for scanner.Scan() {
if v, valid := isValid(scanner.Text()); valid {
sum += v
}
}
return sum, nil
}
func isValid(s string) (int, bool) {
if !re.MatchString(s) {
return 0, false
}
match := re.FindStringSubmatch(s)
i, err := strconv.Atoi(match[2])
if err != nil {
panic(err)
}
l := s[:strings.Index(s, match[2])]
occurences := make(map[uint8]int)
for i := 0; i < len(l); i++ {
c := l[i]
if c == '-' {
continue
}
occurences[c]++
}
var letters []Letter
for k, v := range occurences {
letters = append(letters, Letter{
c: k,
occurence: v,
})
}
sort.Slice(letters, func(i, j int) bool {
a := letters[i]
b := letters[j]
return a.occurence > b.occurence
})
checksum := match[3]
idx := 0
for i := 0; i < len(checksum); i++ {
c := checksum[i]
if letters[idx].occurence != occurences[c] {
return 0, false
}
idx++
}
return i, true
}
type Letter struct {
c uint8
occurence int
}
func fs2(input io.Reader) (int, error) {
scanner := bufio.NewScanner(input)
for scanner.Scan() {
if i := decrypt(scanner.Text()); i != -1 {
return i, nil
}
}
return -1, nil
}
func decrypt(s string) int {
if !re.MatchString(s) {
return -1
}
match := re.FindStringSubmatch(s)
i, err := strconv.Atoi(match[2])
if err != nil {
panic(err)
}
l := s[:strings.Index(s, match[2])]
runes := []rune(l)
var x = uint8(i % 26)
for i := 0; i < len(runes); i++ {
r := uint8(runes[i])
r = ((r-'a')+x)%26 + 'a'
runes[i] = rune(r)
}
if strings.Index(string(runes), "northpole") != -1 {
return i
}
return -1
}