-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day8.swift
62 lines (51 loc) · 1.77 KB
/
Day8.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
import Foundation
let instructions = try String(contentsOfFile: "day8").trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: "\n")
let pattern = #"(\w+) ([+,-]?\d+)"#
let regex = try NSRegularExpression(pattern: pattern, options: [])
var instructionArray = [(String,Int)]()
for instruction in instructions{
let nsrange = NSRange(instruction.startIndex..<instruction.endIndex, in: instruction)
let match = regex.firstMatch(in: instruction, options: [], range: nsrange)
let wordRange = Range(match!.range(at: 1), in: instruction)!
let abbrev = String(instruction[wordRange])
let numRange = Range(match!.range(at: 2), in: instruction)!
let number = Int(instruction[numRange])!
instructionArray.append((abbrev, number))
}
var instructionArrayCpy = instructionArray
for i in 0..<instructionArrayCpy.count{
print("Currently experimenting with line: ", i)
instructionArrayCpy = instructionArray
if instructionArrayCpy[i].0 == "jmp"{
instructionArrayCpy[i].0 = "nop"
}
else if instructionArrayCpy[i].0 == "nop"{
instructionArrayCpy[i].0 = "jmp"
}
else{
print("Accumulator line. Reverting.")
continue
}
var seen = Set<Int>()
var i = 0
var accumulator = 0
while(0 <= i && i < instructionArrayCpy.count && !seen.contains(i)){
seen.insert(i)
switch instructionArrayCpy[i].0{
case "acc":
accumulator += instructionArrayCpy[i].1
i += 1
case "jmp":
i += instructionArrayCpy[i].1
default:
i += 1
}
}
if i == instructionArrayCpy.count{
print("End of file reachced")
print(accumulator)
}
else{
print("Loop reached. Reverting.")
}
}