From fad5da2e2744c2c05630b325c9743dab763ff2af Mon Sep 17 00:00:00 2001 From: Felix Van der Jeugt Date: Sun, 5 Dec 2021 12:10:59 +0100 Subject: [PATCH] add utils, use luajit which seems faster --- day04/part2.lua | 13 +------------ day05/part2.lua | 17 +++++++---------- prepare | 4 +--- run | 5 +++++ utils.lua | 19 +++++++++++++++++++ 5 files changed, 33 insertions(+), 25 deletions(-) create mode 100755 run create mode 100644 utils.lua diff --git a/day04/part2.lua b/day04/part2.lua index 8338b93..cae1590 100644 --- a/day04/part2.lua +++ b/day04/part2.lua @@ -1,15 +1,4 @@ -function split(text, sep) - local parts = {} - local start = 0 - local from, to = text:find(sep) - while from ~= nil do - table.insert(parts, text:sub(start, from - 1)) - text = text:sub(to + 1) - from, to = text:find(sep) - end - table.insert(parts, text) - return parts -end +require("utils") local f = io.open(arg[3]) local numbers = split(f:read("*l"), ",") diff --git a/day05/part2.lua b/day05/part2.lua index 5eeffe3..f1df3ac 100644 --- a/day05/part2.lua +++ b/day05/part2.lua @@ -1,3 +1,5 @@ +require("utils") + function readline() local x1 = io.read("*n") io.read(1) -- "," @@ -16,24 +18,19 @@ function mark(field, x, y) field[x] = row end -function sign(n) - if n == 0 then return 0 - elseif n < 0 then return -1 - else return 1 - end -end +local input = io.open(arg[3]):read("*a") +local lines = split(input, "\n") -io.input(arg[3]) -local x1, y1, x2, y2 = readline() local field = {} -while x1 ~= nil do +for _, line in pairs(lines) do + local x1, y1, x2, y2 = unpack(split(line, "[^0-9]+")) + x1, y1, x2, y2 = tonumber(x1), tonumber(y1), tonumber(x2), tonumber(y2) local x, y, dx, dy = x1, y1, sign(x2 - x1), sign(y2 - y1) mark(field, x, y) while x ~= x2 or y ~= y2 do x, y = x + dx, y + dy mark(field, x, y) end - x1, y1, x2, y2 = readline() end local count = 0 diff --git a/prepare b/prepare index ff04c7b..738fc5c 100755 --- a/prepare +++ b/prepare @@ -5,9 +5,7 @@ part="$2" day="$(printf '%02d' "$day")" if test -f "day${day}/part${part}.lua"; then - luac -o luac.out "day${day}/part${part}.lua" - printf '#!/bin/sh\nlua luac.out "$@"\n' > run - chmod u+x run + luajit -v >/dev/null elif test -f "day${day}/part${part}.hs"; then #stack build stack ghc -- -O3 "day${day}/part${part}.hs" -o run diff --git a/run b/run new file mode 100755 index 0000000..cd1f342 --- /dev/null +++ b/run @@ -0,0 +1,5 @@ +#!/bin/sh +day="$1" +part="$2" + +luajit "day${day}/part${part}.lua" "$@" diff --git a/utils.lua b/utils.lua new file mode 100644 index 0000000..94439b9 --- /dev/null +++ b/utils.lua @@ -0,0 +1,19 @@ +function split(text, sep) + local parts = {} + local start = 0 + local from, to = text:find(sep) + while from ~= nil do + table.insert(parts, text:sub(start, from - 1)) + text = text:sub(to + 1) + from, to = text:find(sep) + end + table.insert(parts, text) + return parts +end + +function sign(n) + if n == 0 then return 0 + elseif n < 0 then return -1 + else return 1 + end +end