Day 3: Gear Ratios
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots
🔓 Edit: Post has been unlocked after 11 minutes
Input parsing AGAIN?
Lua
-- SPDX-FileCopyrightText: 2023 Jummit -- -- SPDX-License-Identifier: GPL-3.0-or-later local lines = {} for line in io.open("3.input"):lines() do table.insert(lines, "."..line..".") end local width = #lines[1] local height = #lines local function at(x, y, w) if y < 1 or y > height then return nil end return lines[y]:sub(x, x + w - 1) end local sum = 0 local gears = {} for y, line in ipairs(lines) do local start = 1 local outLine = line while true do local newStart, numEnd = line:find("%d+", start) if not newStart then break end local symbol = false local num = tonumber(line:sub(newStart, numEnd)) for y = y - 1, y + 1 do local surrounding = at(newStart - 1, y, numEnd - newStart + 3) if surrounding then if surrounding and surrounding:match("[^.%d]") then symbol = true end for i = 1, #surrounding do local gear = surrounding:sub(i, i) == "*" if gear then if not gears[y] then gears[y] = {} end local x = i + newStart - 2 if not gears[y][x] then gears[y][i + newStart - 2] = {} end table.insert(gears[y][x], num) end end end end if symbol then sum = sum + num end start = numEnd + 1 end end print(sum) local ratio = 0 for _, line in pairs(gears) do for _, gears in pairs(line) do if #gears == 2 then ratio = ratio + gears[1] * gears[2] end end end print(ratio)
Hare (Part one only)