use deque in fish solution

This commit is contained in:
Felix Van der Jeugt 2021-12-06 22:02:21 +01:00
parent d99434ac43
commit 563e354df5
No known key found for this signature in database
GPG Key ID: 58B209295023754D
4 changed files with 37 additions and 20 deletions

View File

@ -1,26 +1,26 @@
#!/usr/bin/env luajit
require("utils")
require("deque")
local fishes = {}
local fishes = deque()
for timer = 0, 9 do
fishes[timer] = 0
fishes:append(0)
end
for _, timer in pairs(split(io.open(arg[3]):read("*a"), ",")) do
fishes[tonumber(timer)] = fishes[tonumber(timer)] + 1
fishes:set(tonumber(timer), fishes:get(tonumber(timer)) + 1)
end
for day = 1, 80 do
fishes[9] = (fishes[0] or 0) + (fishes[9] or 0)
fishes[7] = (fishes[0] or 0) + (fishes[7] or 0)
for timer = 0, 9 do
fishes[timer] = fishes[timer + 1]
end
local breeding = fishes:popleft() or 0
fishes:append(0)
fishes:set(8, (fishes:get(8) or 0) + breeding)
fishes:set(6, (fishes:get(6) or 0) + breeding)
end
local sum = 0
for timer, fishday in pairs(fishes) do
sum = sum + fishday
while fishes.size > 0 do
sum = sum + (fishes:pop() or 0)
end
print(sum)

View File

@ -1,26 +1,26 @@
#!/usr/bin/env luajit
require("utils")
require("deque")
local fishes = {}
local fishes = deque()
for timer = 0, 9 do
fishes[timer] = 0
fishes:append(0)
end
for _, timer in pairs(split(io.open(arg[3]):read("*a"), ",")) do
fishes[tonumber(timer)] = fishes[tonumber(timer)] + 1
fishes:set(tonumber(timer), fishes:get(tonumber(timer)) + 1)
end
for day = 1, 256 do
fishes[9] = (fishes[0] or 0) + (fishes[9] or 0)
fishes[7] = (fishes[0] or 0) + (fishes[7] or 0)
for timer = 0, 9 do
fishes[timer] = fishes[timer + 1]
end
local breeding = fishes:popleft() or 0
fishes:append(0)
fishes:set(8, (fishes:get(8) or 0) + breeding)
fishes:set(6, (fishes:get(6) or 0) + breeding)
end
local sum = 0
for timer, fishday in pairs(fishes) do
sum = sum + fishday
while fishes.size > 0 do
sum = sum + (fishes:pop() or 0)
end
print(sum)

View File

@ -14,6 +14,8 @@ function deque()
prepend = prepend,
append = append,
popleft = popleft,
get = get,
set = set,
}
end
@ -79,3 +81,17 @@ function popleft(self)
return nil
end
end
function get(self, i)
if 0 <= i and i < self.size then
return self.elems[(self.start + i) % self.cap]
else
return nil
end
end
function set(self, i, n)
if 0 <= i and i < self.size then
self.elems[(self.start + i) % self.cap] = n
end
end

View File

@ -7,6 +7,7 @@ day="$(printf '%02d' "$day")"
if test -f "day${day}/part${part}.lua"; then
/usr/bin/env luajit -v >/dev/null
cp "day${day}/part${part}.lua" run
chmod u+x run
elif test -f "day${day}/part${part}.hs"; then
#stack build
stack ghc -- -O3 "day${day}/part${part}.hs" -o run