From f2c47597fffa803ea4776335575fbd44221c25c5 Mon Sep 17 00:00:00 2001 From: andrewlalis Date: Mon, 4 Dec 2023 12:00:25 -0500 Subject: [PATCH] Added lua solution for day 1. --- README.md | 3 ++- day_1/solution.lua | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 day_1/solution.lua diff --git a/README.md b/README.md index bc51641..5783564 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ This repository has my solutions for this year's Advent of Code challenges. Each day's challenge will be placed into a directory named `day_N`, where `N` is the day of the challenge. Each day will have a solution program named `solution.*` (with the filetype depending on which programming language I used). -For D programs, you can simply run them with `rdmd solution.d`. +- For D programs, you can simply run them with `rdmd solution.d`. +- For Lua programs, you can run them with `lua solution.lua`. Note that I try and solve the problems as fast as possible, but then I go back and clean up my solution, so what you see isn't really my ugly first attempt. diff --git a/day_1/solution.lua b/day_1/solution.lua new file mode 100644 index 0000000..2472af4 --- /dev/null +++ b/day_1/solution.lua @@ -0,0 +1,56 @@ +local function parseDigits(f, s) + local a = -1 + local b = -1 + for i = 1, #s do + local an = f(s, i) + local bn = f(s, #s - i + 1) + if a == -1 and an ~= -1 then a = an end + if b == -1 and bn ~= -1 then b = bn end + if a ~= -1 and b ~= -1 then break end + end + return a * 10 + b +end + +local function part1() + local f = io.open("part_1_input.txt") + local sum = 0 + local line = f:read("*line") + while line ~= nil do + sum = sum + parseDigits( + function (s, i) + local num = tonumber(string.sub(s, i, i)) + if num ~= nil then return num else return -1 end + end, + line + ) + line = f:read("*line") + end + f:close() + print(sum) +end + +local function part2() + local function findDigit(s, idx) + local num = tonumber(string.sub(s, idx, idx)) + if num ~= nil then return num end + local words = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"} + for i = 1, #words do + local word = words[i] + if #s - idx + 1 >= #word and string.sub(s, idx, idx + #word - 1) == word then + return i + end + end + return -1 + end + local f = io.open("part_2_input.txt") + local sum = 0 + local line = f:read("*line") + while line ~= nil do + sum = sum + parseDigits(findDigit, line) + line = f:read("*line") + end + print(sum) +end + +part1() +part2()