-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain2.go
100 lines (81 loc) · 1.65 KB
/
main2.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
package main
import (
"fmt"
"strings"
)
func main() {
network := parse()
//graphviz(network)
// 4 high pulses from these 4 to `xn` means 1 low pulse
// from `xn` to `rx`, our goal
firstOccurrence := map[string]int{
"fz": 0,
"hn": 0,
"xf": 0,
"mp": 0,
}
count := len(firstOccurrence)
var queue []Message
for i := 1; ; i++ {
queue = append(queue, Button)
var msg Message
for len(queue) > 0 {
msg, queue = queue[0], queue[1:]
// real goal
if msg.To == "rx" && msg.Pulse == LowPulse {
return
}
first, exists := firstOccurrence[msg.From]
if exists && msg.Pulse == HighPulse && first == 0 {
firstOccurrence[msg.From] = i
count--
}
if count == 0 {
var values []int
for _, v := range firstOccurrence {
values = append(values, v)
}
fmt.Println(lcmm(values))
return
}
if network[msg.To] != nil {
queue = append(queue, network[msg.To].Process(msg)...)
}
}
}
}
func lcmm(xs []int) int {
lcm := func(a, b int) int { return a * b / gcd(a, b) }
result := 1
for _, n := range xs {
result = lcm(result, n)
}
return result
}
func gcd(a, b int) int {
for b != 0 {
t := b
b = a % b
a = t
}
return a
}
func graphviz(network Network) {
fmt.Println("digraph {")
fmt.Println(" broadcaster [color=blue]")
fmt.Println(" rx [color=red]")
for k, v := range network {
fmt.Print(k)
fmt.Print(" -> {")
switch m := v.(type) {
case *Conjunction:
fmt.Print(strings.Join(m.Destinations, " "))
case *FlipFlop:
fmt.Print(strings.Join(m.Destinations, " "))
case *Broadcast:
fmt.Print(strings.Join(m.Destinations, " "))
}
fmt.Println("}")
}
fmt.Println("}")
}