-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay02.swift
83 lines (70 loc) · 2.26 KB
/
Day02.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
73
74
75
76
77
78
79
80
81
82
83
import Foundation
import Tools
final class Day02Solver: DaySolver {
let dayNumber: Int = 2
struct Input {
let program: [Int]
}
// private enum Instruction {
// case add(operandIndex1: Int, operandIndex2: Int, targetIndex: Int)
// case mul(operandIndex1: Int, operandIndex2: Int, targetIndex: Int)
// case halt
// }
//
// private func executeProgram(_ originalOrogram: [Int]) -> Int {
// var program = originalOrogram
//
// var ip = 0
//
// instructionLoop: while ip < program.count {
// let instruction: Instruction
//
// switch program[ip] {
// case 1:
// instruction = .add(operandIndex1: program[ip + 1], operandIndex2: program[ip + 2], targetIndex: program[ip + 3])
// case 2:
// instruction = .mul(operandIndex1: program[ip + 1], operandIndex2: program[ip + 2], targetIndex: program[ip + 3])
// case 99:
// instruction = .halt
// default: fatalError("Unknown instruction")
// }
//
// switch instruction {
// case .add(let operandIndex1, let operandIndex2, let targetIndex):
// program[targetIndex] = program[operandIndex1] + program[operandIndex2]
// case .mul(let operandIndex1, let operandIndex2, let targetIndex):
// program[targetIndex] = program[operandIndex1] * program[operandIndex2]
// case .halt:
// break instructionLoop
// }
//
// ip += 4
// }
//
// return program[0]
// }
func solvePart1(withInput input: Input) -> Int {
var program = input.program
program[1] = 12
program[2] = 2
let intcode = IntcodeProcessor()
return intcode.executeProgram(program, input: []).memory[0]
}
func solvePart2(withInput input: Input) -> Int {
let intcode = IntcodeProcessor()
var program = input.program
for noun in 0 ... 99 {
for verb in 0 ... 99 {
program[1] = noun
program[2] = verb
if intcode.executeProgram(program, input: []).memory[0] == 19690720 {
return 100 * noun + verb
}
}
}
return -1
}
func parseInput(rawString: String) -> Input {
return .init(program: rawString.parseCommaSeparatedInts())
}
}