Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 8, 2020 05:54
Show Gist options
  • Save felix-larsen/75abe53999725e704aaaaaab9a9bb757 to your computer and use it in GitHub Desktop.
Save felix-larsen/75abe53999725e704aaaaaab9a9bb757 to your computer and use it in GitHub Desktop.
8th December solution - Advent of Code - swift
print(runInstructions(lines: lines))
var reachedEnd = false
var changeIndex = 0
var accumulator = 0
while !reachedEnd {
(accumulator, reachedEnd) = runInstructions(lines: lines, changeIndex: changeIndex)
changeIndex += 1
}
print(accumulator)
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december08.txt"
let contents = try! String(contentsOfFile: filename)
let lines = contents.components(separatedBy: CharacterSet.newlines)
func runInstructions(lines: [String], changeIndex: Int = -1) -> (Int, Bool) {
var index = 0
var linesRun = Set<Int>()
var accumulator = 0
var instruction = ""
var parameter = 0
var reachedEnd = false
while !linesRun.contains(index) {
linesRun.insert(index)
if index >= lines.count - 1 {
reachedEnd = true
break
}
let line = lines[index]
let instructionAndParameter = line.components(separatedBy: " ")
instruction = instructionAndParameter[0]
parameter = Int(instructionAndParameter[1])!
if instruction == "acc" {
accumulator += parameter
index += 1
} else if instruction == "jmp" {
if index == changeIndex {
index += 1
} else {
index += parameter
}
} else if instruction == "nop" {
if index == changeIndex {
index += parameter
} else {
index += 1
}
}
}
return (accumulator, reachedEnd)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment