aboutsummaryrefslogtreecommitdiff
path: root/03.lua
diff options
context:
space:
mode:
authorJuan Marín Noguera <juan@mnpi.eu>2024-12-03 19:53:12 +0100
committerJuan Marín Noguera <juan@mnpi.eu>2024-12-03 19:53:42 +0100
commit1f393d95c1c8f6793826f05660f575fee2ebe987 (patch)
tree390bc29df28013da0628181b7f64d68ad4c1c91e /03.lua
parent07691021e215b598d986a1709b3b6a6e0a1a031d (diff)
Started switch to Guile Scheme
I want to learn it more than I want to learn Lua right now. And I won't have time for both once the problems are more difficult.
Diffstat (limited to '03.lua')
-rw-r--r--03.lua65
1 files changed, 65 insertions, 0 deletions
diff --git a/03.lua b/03.lua
new file mode 100644
index 0000000..0677236
--- /dev/null
+++ b/03.lua
@@ -0,0 +1,65 @@
+local function parse_instruction (x, y, dont)
+ if dont then return 'dont'
+ elseif x then return {'mul', tonumber(x), tonumber(y)}
+ else return 'do'
+ end
+end
+
+local function input ()
+ local line = ''
+ local start, next_mul, next_do = 1, 0, 0
+ return function ()
+ while true do
+ if next_mul and next_mul < start then
+ next_mul = string.find(line, 'mul', start)
+ end
+ if next_do and next_do < start then
+ next_do = string.find(line, 'do', start)
+ end
+ if next_mul and (not next_do or next_mul < next_do) then
+ start = next_mul + 1
+ local x, y = string.match(line, '^mul%((%d+),(%d+)%)', next_mul)
+ if x then return 'mul', tonumber(x), tonumber(y) end
+ elseif next_do and (not next_mul or next_do < next_mul) then
+ start = next_do + 1
+ if string.match(line, '^do%(%)', next_do) then
+ return 'do'
+ elseif string.match(line, "^don't%(%)", next_do) then
+ return 'dont'
+ end
+ elseif not next_mul and not next_do then
+ line = io.read '*l'
+ if not line then return end
+ start, next_mul, next_do = 1, 0, 0
+ end
+ end
+ end
+end
+
+local funcs = {reader = input()}
+
+function funcs:part1 ()
+ local sum = 0
+ for op, arg1, arg2 in self.reader do
+ if op == 'mul' then sum = sum + arg1 * arg2 end
+ end
+ print(sum)
+end
+
+function funcs:part2()
+ local sum = 0
+ local enabled = true
+ for op, arg1, arg2 in self.reader do
+ print(op, arg1, arg2)
+ if op == 'do' then
+ enabled = true
+ elseif op == 'dont' then
+ enabled = false
+ elseif op == 'mul' then
+ if enabled then sum = sum + arg1 * arg2 end
+ end
+ end
+ print(sum)
+end
+
+return funcs