Created
December 3, 2019 01:37
-
-
Save groob/6e778f975b1477c94b1489898e460ec9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func calculate(_ inputs: [Int], _ idx: Int = 0) -> [Int] { | |
let opcode = inputs[idx] | |
if opcode == 99 { return inputs } | |
let x = inputs[inputs[idx+1]] | |
let y = inputs[inputs[idx+2]] | |
let out = inputs[idx+3] | |
var result : [Int] = inputs | |
switch opcode { | |
case 1: result[out] = x+y | |
case 2: result[out] = x*y | |
default: return result // throw? | |
} | |
return calculate(result, idx+4) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Computer { | |
private let initialState : [Int] | |
private var memory : [Int] | |
private var index : Int = 0 | |
init(state: [Int]) { | |
self.initialState = state | |
self.memory = state | |
} | |
enum OSError: Error { | |
case InvalidOpcode | |
} | |
private func step() throws { | |
let opcode = memory[index] | |
let p1 = memory[memory[index+1]] | |
let p2 = memory[memory[index+2]] | |
switch opcode { | |
case 1: memory[memory[index+3]] = p1 + p2 | |
case 2: memory[memory[index+3]] = p1 * p2 | |
default: throw OSError.InvalidOpcode | |
} | |
self.index = index+4 | |
} | |
private func reset(noun: Int, verb: Int) { | |
self.reset() | |
memory[1] = noun | |
memory[2] = verb | |
} | |
private func run() throws { | |
while memory[index] != 99 { | |
try step() | |
} | |
} | |
private func reset() { | |
self.memory = initialState | |
self.index = 0 | |
} | |
func run(noun: Int, verb: Int) throws -> Int { | |
self.reset(noun: noun, verb: verb) | |
try self.run() | |
return memory[0] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment