-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
132 lines (114 loc) · 2.15 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"io"
"math/big"
"strings"
lib "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader, nb, n int) int {
lines := lib.ReaderToStrings(input)
var funcs []apply
for _, line := range lines {
del := lib.NewDelimiter(line, " ")
if strings.Contains(line, "deal with") {
funcs = append(funcs, increment(del.GetInt(3)))
} else if strings.Contains(line, "cut") {
funcs = append(funcs, cut(del.GetInt(1)))
} else if strings.Contains(line, "deal") {
funcs = append(funcs, deal())
} else {
panic(line)
}
}
cards := make([]int, nb)
for i := 0; i < nb; i++ {
cards[i] = i
}
for _, f := range funcs {
cards = f(cards)
}
for i, card := range cards {
if card == n {
return i
}
}
return -1
}
type apply func([]int) []int
func deal() apply {
return func(s []int) []int {
l := 0
r := len(s) - 1
for l < r {
s[l], s[r] = s[r], s[l]
l++
r--
}
return s
}
}
func increment(n int) apply {
return func(s []int) []int {
res := make([]int, len(s))
res[0] = s[0]
count := 1
idx := 0
for {
idx = (idx + n) % len(s)
res[idx] = s[count]
count++
if count == len(s) {
break
}
}
return res
}
}
func cut(n int) apply {
return func(s []int) []int {
v := 0
if n == 0 {
return s
}
if n >= 0 {
v = len(s) - n
} else {
v = -n
}
deal()(s)
deal()(s[:v])
deal()(s[v:])
return s
}
}
func fs2(input io.Reader, l, times, index int64) int64 {
v := big.NewInt(index)
m := big.NewInt(l)
t := big.NewInt(times)
i := big.NewInt(0)
d := big.NewInt(1)
lines := lib.ReaderToStrings(input)
for _, line := range lines {
del := lib.NewDelimiter(line, " ")
if strings.Contains(line, "deal with") {
x := big.NewInt(int64(del.GetInt(3)))
x.ModInverse(x, m)
d.Mul(d, x)
} else if strings.Contains(line, "cut") {
x := big.NewInt(int64(del.GetInt(1)))
i.Add(i, x.Mul(x, d))
} else if strings.Contains(line, "deal") {
d.Neg(d)
i.Add(i, d)
} else {
panic(line)
}
}
a := big.NewInt(1)
a.Sub(a, d).ModInverse(a, m)
d.Exp(d, t, m)
it := big.NewInt(1)
it.Sub(it, d).Mul(it, a).Mul(it, i)
v.Mul(v, d).Add(v, it).Mod(v, m)
return v.Int64()
}