-
Notifications
You must be signed in to change notification settings - Fork 0
/
day09.swift
executable file
·75 lines (53 loc) · 1.88 KB
/
day09.swift
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
#!/usr/bin/swift
import Foundation
class Marble {
let number: Int
var left: Marble?
var right: Marble?
init(_ number: Int) {
self.number = number
}
static func != (lhs: Marble, rhs: Marble) -> Bool {
return lhs.number != rhs.number
}
func insert(_ newMarble: Marble, nextToCurrentMarble current: Marble) {
let marbleLeftOfInsert = current.right
let marbleRightOfInsert = marbleLeftOfInsert!.right
marbleLeftOfInsert!.right = newMarble
marbleRightOfInsert!.left = newMarble
newMarble.left = marbleLeftOfInsert
newMarble.right = marbleRightOfInsert
}
static func remove(forCurrentMarble marble: Marble) -> (newCurrent: Marble, removedValue: Int) {
var toRemove = marble
for _ in 0..<7 {
toRemove = toRemove.left!
}
let newCurrent = toRemove.right!
newCurrent.left = toRemove.left!
newCurrent.left?.right = newCurrent
return (newCurrent, toRemove.number)
}
}
let numberOfPlayers = 448
let lastMarblePoints = 7162800
var currentMarble = Marble(0)
currentMarble.left = currentMarble
currentMarble.right = currentMarble
var playerNumber = 0
var playerScores: [ Int : Int ] = [:]
for marbleNumber in 1...lastMarblePoints {
if marbleNumber % 23 == 0 {
playerScores[playerNumber, default: 0] += marbleNumber
let removeResult = Marble.remove(forCurrentMarble: currentMarble)
playerScores[playerNumber, default: 0] += removeResult.removedValue
currentMarble = removeResult.newCurrent
} else {
let newMarble = Marble(marbleNumber)
currentMarble.insert(newMarble, nextToCurrentMarble: currentMarble)
currentMarble = newMarble
}
playerNumber = (playerNumber + 1) % numberOfPlayers
}
let highestScore = playerScores.max { $0.value < $1.value }
print(highestScore!.value)