diff --git a/solutions/day03/example2.txt b/solutions/day03/example2.txt new file mode 100644 index 0000000..30032cb --- /dev/null +++ b/solutions/day03/example2.txt @@ -0,0 +1 @@ +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) diff --git a/solutions/day03/solution.nim b/solutions/day03/solution.nim index d491a22..39c7305 100644 --- a/solutions/day03/solution.nim +++ b/solutions/day03/solution.nim @@ -3,12 +3,9 @@ import aoc proc parseInstruction(i: string): (int, int) = let s = i.split(',') - echo s assert s.len == 2 result = (parseInt(s[0]), parseInt(s[1])) - - proc parseInput(input: string): seq[(int, int)] = var i: int while i < input.len: @@ -35,21 +32,59 @@ proc parseInput(input: string): seq[(int, int)] = inc i else: inc i - - # var xy: (int, int) - - proc partOne*(input: string): int = let instructions = parseInput(input) instructions.mapIt(it[0] * it[1]).sum() +proc parseInput2(input: string): seq[(int, int)] = + var i: int + var working = true + while i < input.len: + case input[i] + of 'd': + # check for enough room for don't() + if i > (input.len - 6): inc i + else: + if input[i .. i + 3] == "do()": + working = true + i += 3 + elif input[i .. i + 6] == "don't()": + working = false + i += 6 + inc i + of 'm': + # ul(x,y) + # not enough space for instruction so bail + if i > (input.len - 6): return + else: + var instruction: string + if input[i .. i+3] == "mul(": + i += 4 + while true: + let c = input[i] + case c: + of '0'..'9': + instruction.add c; inc i + of ')': + if working: + result.add parseInstruction instruction + break + of ',': + instruction.add c; inc i + else: break + inc i + else: inc i + + +proc partTwo*(input: string): int = + let instructions = parseInput2(input) + instructions.mapIt(it[0] * it[1]).sum() -# proc partTwo*(input: string): int = 0 -# solve: "example.txt": partOne: 161 - # partTwo: 0 + "example2.txt": + partTwo: 48 "input.txt": - partOne: 0 - # partTwo: 0 + partOne: 164730528 + partTwo: 70478672