68 lines
2.2 KiB
Lua
68 lines
2.2 KiB
Lua
#!/usr/bin/env lua
|
|
--[[
|
|
This cursed script generates SQL statements to be sent to a SQLite database
|
|
and returns two lines with two aunt IDs, for each part of the puzzle.
|
|
|
|
Usage: lua5.3 part1.lua <input | sqlite3
|
|
--]]
|
|
|
|
local sues = {}
|
|
|
|
for line in io.lines() do
|
|
local _, data_start, i = line:find('^Sue (%d+): ')
|
|
i = tonumber(i)
|
|
sues[i] = {}
|
|
for key, value in line:sub(data_start):gmatch('(%w+): (%d+)') do
|
|
sues[i][key] = tonumber(value)
|
|
end
|
|
end
|
|
|
|
local compounds = {
|
|
{name='children', expected=3, operator='='},
|
|
{name='cats', expected=7, operator='>'},
|
|
{name='samoyeds', expected=2, operator='='},
|
|
{name='pomeranians', expected=3, operator='<'},
|
|
{name='akitas', expected=0, operator='='},
|
|
{name='vizslas', expected=0, operator='='},
|
|
{name='goldfish', expected=5, operator='<'},
|
|
{name='trees', expected=3, operator='>'},
|
|
{name='cars', expected=2, operator='='},
|
|
{name='perfumes', expected=1, operator='='},
|
|
}
|
|
|
|
local columns = {}
|
|
for _, compound in pairs(compounds) do
|
|
table.insert(columns, compound.name .. ' INTEGER')
|
|
end
|
|
|
|
print(string.format('CREATE TABLE sue (id INTEGER NOT NULL PRIMARY KEY, %s);', table.concat(columns, ", ")))
|
|
|
|
local values = {}
|
|
for i, sue in pairs(sues) do
|
|
local value = {i}
|
|
for _, compound in pairs(compounds) do
|
|
table.insert(value, sue[compound.name] or 'NULL')
|
|
end
|
|
table.insert(values, string.format('(%s)', table.concat(value, ', ')))
|
|
end
|
|
|
|
print(string.format('INSERT INTO sue VALUES %s;', table.concat(values, ', ')))
|
|
|
|
-- Part 1 uses only the '=' operator (exact match), but part 2 uses ranges depending on the compound
|
|
local function build_conditions(operator_override)
|
|
local conditions = {}
|
|
for _, compound in pairs(compounds) do
|
|
table.insert(conditions, string.format(
|
|
'(%s IS NULL OR %s %s %d)',
|
|
compound.name,
|
|
compound.name,
|
|
operator_override or compound.operator,
|
|
compound.expected
|
|
))
|
|
end
|
|
return conditions
|
|
end
|
|
|
|
print(string.format('SELECT id FROM sue WHERE %s;', table.concat(build_conditions('='), ' AND ')))
|
|
print(string.format('SELECT id FROM sue WHERE %s;', table.concat(build_conditions(), ' AND ')))
|