Compare commits

...

10 Commits

10 changed files with 465 additions and 57 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
.vscode
res/inputs

17
README.md Normal file
View File

@@ -0,0 +1,17 @@
# Advent of Code
This repo contains my attempt at this year's Advent of Code (2025)
I will solve this AoC using Lua in the context of the ComputerCraft Minecraft mod.\
This project can also be run using the amazing [CraftOS-PC emulator](https://github.com/MCJack123/craftos2)
## Progress
<!-- calendar-start -->
#### Stars: 0/24
|Mon|Tue|Wed|Thu|Fri|Sat|Sun|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|1<br>|2<br>|3<br>|4<br>|5<br>|6<br>|7<br>|
|8<br>|9<br>|10<br>|11<br>|12<br>|||
<!-- calendar-end -->

View File

@@ -48,4 +48,3 @@
"puzzle2": false
}
}

125
src/calendar.lua Normal file
View File

@@ -0,0 +1,125 @@
package.path = "/aoc/src/lib/?.lua;" .. package.path
require("aoc")
local json = require("json")
local utils = require("utils")
local buffer = require("buffer")
local stats = json.loads(utils.readFile(RES_PATH .. "/stats.json")) or {}
local readmePath = ROOT_PATH .. "/README.md"
local outBuf = buffer.Buffer.new()
local function insertInReadme()
local body = utils.readFile(readmePath) or ""
local tagStart = "<!-- calendar-start -->"
local tagEnd = "<!-- calendar-end -->"
body = body:gsub(
tagStart:gsub("%-", "%%-") .. ".-" .. tagEnd:gsub("%-", "%%-"),
tagStart .. "\n" .. outBuf:tostring() .. tagEnd
)
utils.writeFile(readmePath, body, true)
end
local totalStars = 0
for _, s in pairs(stats) do
if s.puzzle1 then totalStars = totalStars + 1 end
if s.puzzle2 then totalStars = totalStars + 1 end
end
local startTS = 1764543600
local startDate = os.date("*t", startTS)
local firstWeekday = (startDate.wday + 5) % 7
local padding = {x=3, y=1}
local dayNames = {
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
}
local day = -firstWeekday + 1
local rowSep = "+"
local padRow = "|"
for _ = 1, 7 do
rowSep = rowSep .. string.rep("-", padding.x * 2 + 3) .. "+"
padRow = padRow .. string.rep(" ", padding.x * 2 + 3) .. "|"
end
local function printRow(cells, cellWidth, padding)
local xPad = string.rep(" ", padding.x)
local height = 0
for _, cell in ipairs(cells) do
height = math.max(height, type(cell) == "string" and 1 or #cell)
end
for i = -padding.y + 1, height + padding.y do
write("|")
for _, cell in ipairs(cells) do
local text = cell[i] or ""
if type(cell) == "string" and i == 1 then
text = cell
end
local pad = cellWidth - #text
local lPad = math.ceil(pad / 2)
local rPad = pad - lPad
write(xPad .. string.rep(" ", lPad))
if i > 1 and i <= height then
term.setTextColor(colors.orange)
end
write(text)
term.setTextColor(colors.white)
write(string.rep(" ", rPad) .. xPad .. "|")
end
print()
end
print(rowSep)
end
term.clear()
term.setCursorPos(1, 1)
term.setTextColor(colors.white)
print(("Stars: %d/24"):format(totalStars, 24))
outBuf:print(("#### Stars: %d/24\n"):format(totalStars, 24))
print(rowSep)
printRow(dayNames, 3, padding)
outBuf:print("|" .. table.concat(dayNames, "|") .. "|")
for _ = 1, 7 do
outBuf:write("|:-:")
end
outBuf:print("|")
while day < 12 do
local row = {}
local outRow = {}
for _ = 1, 7 do
if day < 1 or day > 12 then
table.insert(row, "")
table.insert(outRow, "")
else
local dayStats = stats[("day%02d"):format(day)]
local stars = 0
if dayStats.puzzle1 then stars = stars + 1 end
if dayStats.puzzle2 then stars = stars + 1 end
local cell = {
tostring(day),
string.rep("\x04", stars, " ")
}
table.insert(row, cell)
cell = {
tostring(day),
string.rep(":star:", stars, "")
}
table.insert(outRow, table.concat(cell, "<br>"))
end
day = day + 1
end
printRow(row, 3, padding)
outBuf:print("|" .. table.concat(outRow, "|") .. "|")
end
insertInReadme()
---@diagnostic disable-next-line: undefined-field
term.screenshot()
os.sleep(2)

View File

@@ -1,5 +1,7 @@
SRC_PATH = "/aoc/src"
RES_PATH = "/aoc/res"
ROOT_PATH = "/aoc"
SRC_PATH = ROOT_PATH .. "/src"
RES_PATH = ROOT_PATH .. "/res"
CACHE_PATH = "/.cache/aoc"
package.path = SRC_PATH .. "/lib/?.lua;" .. package.path
@@ -9,9 +11,11 @@ END_DATE = {day=12, month=12, year=2025}
local json = require("json")
local dates = require("dates")
local days = require("days")
local progress = require "progress"
local today = os.date("*t")
local aoc = {}
local function loadStats(path)
function aoc.loadStats(path)
path = shell.resolve(path)
if not fs.exists(path) then
printError("Stats file not found (" .. path .. ")")
@@ -27,7 +31,7 @@ local function loadStats(path)
return data
end
local function printDateInfo()
function aoc.printDateInfo()
if dates.isBefore(START_DATE, today) then
print("AoC 2025 has not started yet")
return
@@ -40,7 +44,7 @@ local function printDateInfo()
print("Day " .. day .. "/" .. END_DATE.day)
end
local function printStats(stats, selected)
function aoc.printStats(stats, selected)
local keys = {}
for k in pairs(stats) do
table.insert(keys, k)
@@ -55,43 +59,50 @@ local function printStats(stats, selected)
local date = {day=day, month=START_DATE.month, year=START_DATE.year}
term.setTextColor(colors.lightBlue)
if selected == day then
term.setBackgroundColor(colors.gray)
write("- ")
else
term.setBackgroundColor(colors.black)
write(" ")
end
if not dates.isBefore(date, today) then
term.setTextColor(colors.white)
else
term.setTextColor(colors.gray)
term.setTextColor(colors.lightGray)
end
write(string.format("Day %2s ", day))
if value.puzzle1 then
term.setTextColor(colors.orange)
stars = stars + 1
else
term.setTextColor(colors.gray)
term.setTextColor(colors.lightGray)
end
write("\x04")
if value.puzzle2 then
term.setTextColor(colors.orange)
stars = stars + 1
else
term.setTextColor(colors.gray)
term.setTextColor(colors.lightGray)
end
write("\x04")
term.setTextColor(colors.white)
print()
print(" ")
end
term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
write(string.format("You have %d", stars))
term.setTextColor(colors.orange)
write("\x04")
write("\x04 ")
local x, y = term.getCursorPos()
progress.bar(x, y, 20, stars, 24, colors.orange, colors.gray)
term.setTextColor(colors.white)
print()
print()
print("Press END to quit")
end
local function printBanner()
function aoc.printBanner()
term.setTextColor(colors.green)
print("+--------------------------------------+")
print("| Welcome to the Advent of Code 2025 |")
@@ -99,8 +110,8 @@ local function printBanner()
term.setTextColor(colors.white)
end
local function main()
local stats = loadStats("aoc/res/stats.json")
function aoc.main()
local stats = aoc.loadStats("aoc/res/stats.json") or {}
local selectedDay = math.max(1, math.min(END_DATE.day, today.day))
if not dates.isInDateRange(START_DATE, today, END_DATE) then
selectedDay = 1
@@ -109,9 +120,9 @@ local function main()
while true do
term.clear()
term.setCursorPos(1, 1)
printBanner()
printDateInfo()
printStats(stats, selectedDay)
aoc.printBanner()
aoc.printDateInfo()
aoc.printStats(stats, selectedDay)
local event, key, is_held = os.pullEvent("key")
if key == keys.up then
@@ -128,8 +139,9 @@ local function main()
dayStats.puzzle2
)
day:show()
stats = aoc.loadStats("aoc/res/stats.json") or {}
end
end
end
main()
return aoc

35
src/lib/buffer.lua Normal file
View File

@@ -0,0 +1,35 @@
local buffer = {}
---@class Buffer
local Buffer = {_buf=""}
Buffer.__index = Buffer
---Creates a new buffer
---@param str string?
---@return Buffer
function Buffer.new(str)
local buf = {}
buf._buf = str or ""
setmetatable(buf, Buffer)
return buf
end
function Buffer:tostring()
return self._buf
end
function Buffer:clear()
self._buf = ""
end
function Buffer:write(text)
self._buf = self._buf .. (text or "")
end
function Buffer:print(text)
self:write((text or "") .. "\n")
end
buffer.Buffer = Buffer
return buffer

View File

@@ -1,14 +1,8 @@
local json = require("json")
local utils = require("utils")
local days = {}
local DAY_CACHE_PATH = "/.cache/days"
local CHOICES = {
create = "Create files",
example = "Run examples",
real = "Run with real input",
main = "Back to main menu"
}
local DAY_CACHE_PATH = CACHE_PATH .. "/days"
local PUZZLE_BASE = [[local puzzle%d = {}
@@ -24,7 +18,8 @@ return puzzle%d
---@field title string?
---@field puzzle1 boolean
---@field puzzle2 boolean
local Day = {day = 0, title = nil, puzzle1 = false, puzzle2 = false}
---@field results table
local Day = {day = 0, title = nil, puzzle1 = false, puzzle2 = false, results={}}
Day.__index = Day
---Creates a new Day object
@@ -38,9 +33,14 @@ function Day.new(dayI, puzzle1, puzzle2)
day.day = dayI
day.puzzle1 = puzzle1
day.puzzle2 = puzzle2
day:loadResults()
return day
end
function Day:cacheDir()
return DAY_CACHE_PATH .. ("/%02d"):format(self.day)
end
---Returns the title of this day.
---
---This function looks in the following places, in order:
@@ -52,7 +52,7 @@ function Day:getTitle()
if self.title then
return self.title
end
local cachePath = DAY_CACHE_PATH .. ("/%02d.txt"):format(self.day)
local cachePath = self:cacheDir() .. "/name.txt"
if fs.exists(cachePath) then
local cache = fs.open(cachePath, "r")
if cache then
@@ -64,7 +64,7 @@ function Day:getTitle()
end
end
end
fs.makeDir(DAY_CACHE_PATH)
fs.makeDir(self:cacheDir())
local res = http.get("https://adventofcode.com/2024/day/" .. self.day)
local title = "Day " .. self.day
if res then
@@ -125,31 +125,119 @@ function Day:getInputData()
return utils.readFile(self:inputPath())
end
function Day:execPuzzle(puzzleI, data)
local puzzle = require(self:srcDir() .. "/puzzle" .. puzzleI)
function Day:getResultKey(real, puzzle, suffix)
local key = ""
if real then
key = "input"
else
key = "example"
if suffix then
key = key .. "_" .. suffix
end
end
key = key .. "-" .. puzzle
return key
end
function Day:execPuzzle(puzzleI, data, resultKey)
local path = self:srcDir() .. "/puzzle" .. puzzleI
package.loaded[path] = nil
local puzzle = require(path)
local t0 = os.epoch("local")
local result = puzzle.solve(data)
local t1 = os.epoch("local")
print(("(Executed in %.3fs)"):format((t1 - t0) / 1000))
print("Result:", result)
self.results[resultKey] = result
self:saveResults()
end
function Day:execExample(puzzleI, suffix)
local data = self:getExampleData(suffix)
return self:execPuzzle(puzzleI, data)
return self:execPuzzle(puzzleI, data, self:getResultKey(false, puzzleI, suffix))
end
function Day:execReal(puzzleI)
local data = self:getInputData()
return self:execPuzzle(puzzleI, data)
return self:execPuzzle(puzzleI, data, self:getResultKey(true, puzzleI))
end
function Day:choosePuzzle()
function Day:choosePuzzle(real)
self:printTitle()
local c = utils.promptChoices({"Puzzle 1", "Puzzle 2", "Back"})
local choices = {
{"Puzzle 1", 1},
{"Puzzle 2", 2},
"Back"
}
local res1 = self.results[self:getResultKey(real, 1)]
local res2 = self.results[self:getResultKey(real, 2)]
if res1 then choices[1][1] = choices[1][1] .. (" - %s"):format(res1) end
if res2 then choices[2][1] = choices[2][1] .. (" - %s"):format(res2) end
local c = utils.promptChoices(choices)
return c
end
function Day:menuStars()
local solvedTxt = function (b)
if b then
return "solved"
end
return "unsolved"
end
local c0 = 1
while true do
self:printTitle()
local choices = {
{"Mark puzzle 1 as " .. solvedTxt(not self.puzzle1), 1},
{"Mark puzzle 2 as " .. solvedTxt(not self.puzzle2), 2},
"Back"
}
local c = utils.promptChoices(choices, c0)
if c == "Back" then
return
end
c0 = c
if c == 1 then
self.puzzle1 = not self.puzzle1
elseif c == 2 then
self.puzzle2 = not self.puzzle2
end
self:saveStats()
end
end
function Day:saveStats()
local path = RES_PATH .. "/stats.json"
local content = utils.readFile(path) or "{}"
local data = json.loads(content) or {}
data[("day%02d"):format(self.day)] = {
puzzle1=self.puzzle1,
puzzle2=self.puzzle2,
}
content = json.dumps(data, 4, true)
utils.writeFile(path, content, true)
end
function Day:loadResults()
local path = self:cacheDir() .. "/results.json"
local results = {}
if fs.exists(path) then
local data = utils.readFile(path)
local r = json.loads(data)
if type(r) == "table" then
results = r
end
end
self.results = results
end
function Day:saveResults()
local data = json.dumps(self.results)
fs.makeDir(self:cacheDir())
local path = self:cacheDir() .. "/results.json"
utils.writeFile(path, data, true)
end
function Day:printTitle()
term.clear()
term.setCursorPos(1, 1)
@@ -163,28 +251,35 @@ function Day:show()
while true do
self:printTitle()
if fs.exists(self:srcDir()) then
local c = utils.promptChoices({CHOICES.example, CHOICES.real, CHOICES.main})
if c == CHOICES.main then
local c = utils.promptChoices({
{"Run examples", "examples"},
{"Run with real input", "inputs"},
{"Mark solved", "stars"},
{"Back to main menu", "main"}
})
if c == "main" then
return
end
local puzzle = self:choosePuzzle()
elseif c == "stars" then
self:menuStars()
else
local puzzle = self:choosePuzzle(c == "inputs")
if puzzle ~= "Back" then
local puzzleI = ({
["Puzzle 1"] = 1,
["Puzzle 2"] = 2
})[puzzle]
if c == CHOICES.example then
self:execExample(puzzleI)
elseif c == CHOICES.real then
self:execReal(puzzleI)
if c == "examples" then
self:execExample(puzzle)
elseif c == "inputs" then
self:execReal(puzzle)
end
utils.waitForKey(keys.enter)
end
end
else
local c = utils.promptChoices({CHOICES.create, CHOICES.main})
if c == CHOICES.main then
local c = utils.promptChoices({
{"Create files", "create"},
{"Back to main menu", "main"}
})
if c == "main" then
return
elseif c == CHOICES.create then
elseif c == "create" then
self:createFiles()
end
end

View File

@@ -20,6 +20,13 @@ local function errFactory(prefix)
end
end
local function ifNil(test, ifNil, ifNotNil)
if test == nil then
return ifNil
end
return ifNotNil
end
local function parseObj(data)
local printErr = errFactory("Error while parsing object")
local obj = {}
@@ -199,4 +206,86 @@ function json.loads(data)
return res
end
local function kind(obj)
if type(obj) ~= "table" then
return type(obj)
end
local i = 1
for _ in pairs(obj) do
if obj[i] ~= nil then
i = i + 1
else
return "table"
end
end
if i == 1 then
return "table"
end
return "array"
end
local function escapeStr(str)
local in_char = {'\\', '"', '/', '\b', '\f', '\n', '\r', '\t'}
local out_char = {'\\', '"', '/', 'b', 'f', 'n', 'r', 't'}
for i, c in ipairs(in_char) do
str = str:gsub(c, '\\' .. out_char[i])
end
return str
end
function json.dumps(data, indent, sortKeys, depth)
if data == json.null then
return "null"
end
local t = kind(data)
if t == "string" then
return '"' .. escapeStr(data) .. '"'
elseif t == "number" or t == "boolean" then
return tostring(data)
end
depth = depth or 0
local spaces = ""
if indent ~= nil then
spaces = string.rep(" ", indent * depth)
end
local res = ""
if t == "array" then
res = res .. "[" .. ifNil(indent, "", "\n")
for i, val in ipairs(data) do
if i > 1 then
res = res .. "," .. ifNil(indent, " ", "\n")
end
res = res .. spaces .. string.rep(" ", indent or 0)
res = res .. json.dumps(val, indent, sortKeys, depth + 1)
end
res = res .. ifNil(indent, "", "\n") .. spaces .. "]"
elseif t == "table" then
res = res .. "{" .. ifNil(indent, "", "\n")
local first = true
local keys = {}
for k, _ in pairs(data) do
table.insert(keys, k)
end
if sortKeys then
table.sort(keys)
end
for _, k in ipairs(keys) do
local v = data[k]
if not first then
res = res .. "," .. ifNil(indent, " ", "\n")
end
first = false
res = res .. spaces .. string.rep(" ", indent or 0)
res = res .. '"' .. escapeStr(k) .. '": '
res = res .. json.dumps(v, indent, sortKeys, depth + 1)
end
res = res .. ifNil(indent, "", "\n") .. spaces .. "}"
end
return res
end
return json

14
src/lib/progress.lua Normal file
View File

@@ -0,0 +1,14 @@
local utils = require("utils")
local progress = {}
function progress.bar(x, y, width, value, max, fg, bg)
local fgWidth = utils.round(value * width / max)
fgWidth = math.max(0, math.min(width, fgWidth))
paintutils.drawLine(x, y, x + width - 1, y, bg)
if fgWidth > 0 then
paintutils.drawLine(x, y, x + fgWidth - 1, y, fg)
end
term.setBackgroundColor(colors.black)
end
return progress

View File

@@ -1,7 +1,7 @@
local utils = {}
function utils.promptChoices(choices)
local c = 1
function utils.promptChoices(choices, default)
local c = default or 1
local ox, oy = term.getCursorPos()
while true do
term.setCursorPos(ox, oy)
@@ -11,7 +11,11 @@ function utils.promptChoices(choices)
else
term.setTextColor(colors.lightGray)
end
print(choice)
local label = choice
if type(choice) == "table" then
label = choice[1] or choice["label"]
end
print(label)
end
local event, key, is_held = os.pullEvent("key")
if key == keys.up then
@@ -23,7 +27,11 @@ function utils.promptChoices(choices)
end
end
term.setTextColor(colors.white)
return choices[c]
local choice = choices[c]
if type(choice) == "table" then
choice = choice[2] or choice["value"]
end
return choice
end
function utils.readFile(path)
@@ -70,4 +78,16 @@ function utils.waitForKey(targetKey)
end
end
function utils.splitLines(data)
local t = {}
for str in string.gmatch(data, "([^\n]+)") do
table.insert(t, str)
end
return t
end
function utils.round(x)
return x >= 0 and math.floor(x + 0.5) or math.ceil(x - 0.5)
end
return utils