Fixed Day6 second star and setup functions to make loading of file easier
This commit is contained in:
45
2025/Day6/Day6_2nd.lua
Normal file
45
2025/Day6/Day6_2nd.lua
Normal file
@@ -0,0 +1,45 @@
|
||||
-- Day 6 Lua
|
||||
--
|
||||
require("functions")
|
||||
local input_file = "Day6/full"
|
||||
local input = file_characters_to_table(input_file)
|
||||
local rows = tablelength(input)
|
||||
local cols = tablelength(input[1])
|
||||
local grandtotal = 0
|
||||
|
||||
local math = {}
|
||||
for col = cols, 1, -1 do
|
||||
local num = ""
|
||||
local calc = ""
|
||||
for row = 1, rows do
|
||||
-- print("Checking R" .. row .. "C" .. col .. " " .. input[row][col])
|
||||
v = input[row][col]
|
||||
if tonumber(v) ~= nil then
|
||||
num = num .. input[row][col]
|
||||
elseif v == "*" or v == "+" then
|
||||
calc = v
|
||||
end
|
||||
end
|
||||
table.insert(math, tonumber(num))
|
||||
-- print("Adding " .. num)
|
||||
if calc == "*" or calc == "+" then
|
||||
local t = 0
|
||||
for k, v in ipairs(math) do
|
||||
if t == 0 then
|
||||
t = v
|
||||
else
|
||||
if calc == "+" then
|
||||
t = t + v
|
||||
end
|
||||
if calc == "*" then
|
||||
t = t * v
|
||||
end
|
||||
end
|
||||
end
|
||||
print(calc .. " " .. t)
|
||||
grandtotal = grandtotal + t
|
||||
math = {}
|
||||
end
|
||||
end
|
||||
print()
|
||||
print("Grand total = " .. grandtotal)
|
||||
28
2025/functions.lua
Normal file
28
2025/functions.lua
Normal file
@@ -0,0 +1,28 @@
|
||||
function file_lines_to_table(filename)
|
||||
local file = {}
|
||||
for line in io.lines(filename) do
|
||||
table.insert(file, line)
|
||||
end
|
||||
return file
|
||||
end
|
||||
|
||||
function file_characters_to_table(filename)
|
||||
local file = {}
|
||||
for line in io.lines(filename) do
|
||||
local lineelements = {}
|
||||
for I = 1, string.len(line) do
|
||||
c = string.sub(line, I, I)
|
||||
table.insert(lineelements, c)
|
||||
end
|
||||
table.insert(file, lineelements)
|
||||
end
|
||||
return file
|
||||
end
|
||||
|
||||
function tablelength(T)
|
||||
local count = 0
|
||||
for _ in pairs(T) do
|
||||
count = count + 1
|
||||
end
|
||||
return count
|
||||
end
|
||||
Reference in New Issue
Block a user