@@ -88,5 +88,62 @@ public func part1() -> Int {
88
88
}
89
89
90
90
public func part2( ) -> Int {
91
- 0
91
+ var monkeys = [ Monkey] ( )
92
+ var id = 0
93
+ var items = [ Int] ( )
94
+ var op = Operation . plus
95
+ var constant = 0
96
+ var divisible = 0
97
+ var ifTrue = 0
98
+ var ifFalse = 0
99
+ for line in stringsFromFile ( ) {
100
+ if line. hasPrefix ( " Monkey " ) {
101
+ id = Int ( line. replacingOccurrences ( of: " : " , with: " " ) . split ( separator: " " ) . last!) !
102
+ } else if line. hasPrefix ( " Starting items: " ) {
103
+ items = line. replacingOccurrences ( of: " , " , with: " " ) . split ( separator: " " ) . dropFirst ( 2 ) . compactMap { Int ( $0) ! }
104
+ } else if line. hasPrefix ( " Operation " ) {
105
+ if line. contains ( " old * old " ) {
106
+ op = . square
107
+ constant = 1
108
+ } else {
109
+ constant = Int ( line. split ( separator: " " ) . last!) !
110
+ op = line. contains ( " old + " ) ? . plus : . multiply
111
+ }
112
+ } else if line. hasPrefix ( " Test " ) {
113
+ divisible = Int ( line. split ( separator: " " ) . last!) !
114
+ } else if line. hasPrefix ( " If true " ) {
115
+ ifTrue = Int ( line. split ( separator: " " ) . last!) !
116
+ } else if line. hasPrefix ( " If false " ) {
117
+ ifFalse = Int ( line. split ( separator: " " ) . last!) !
118
+ monkeys. append ( Monkey ( id: id, items: items, op: op, constant: constant, divisible: divisible, ifTrue: ifTrue, ifFalse: ifFalse) )
119
+ }
120
+ }
121
+
122
+ let lcm = monkeys. reduce ( 1 ) { $0 * $1. divisible }
123
+
124
+ func inspect( monkey id: Int ) {
125
+ let items = monkeys [ id] . items
126
+ monkeys [ id] . items = [ ]
127
+ for item in items {
128
+ var worry = item
129
+ worry = monkeys [ id] . op. apply ( worry: worry, constant: monkeys [ id] . constant)
130
+ worry %= lcm
131
+ if worry % monkeys[ id] . divisible == 0 {
132
+ monkeys [ monkeys [ id] . ifTrue] . items. append ( worry)
133
+ } else {
134
+ monkeys [ monkeys [ id] . ifFalse] . items. append ( worry)
135
+ }
136
+ monkeys [ id] . inspections += 1
137
+ }
138
+ }
139
+
140
+ for _ in 0 ..< 10000 {
141
+ for i in 0 ..< ( monkeys. count) {
142
+ inspect ( monkey: i)
143
+ }
144
+ }
145
+
146
+ monkeys. sort { $0. inspections > $1. inspections }
147
+
148
+ return monkeys [ 0 ] . inspections * monkeys[ 1 ] . inspections
92
149
}
0 commit comments