reorg and add code for second edition

This commit is contained in:
Aditya Bhargava
2023-08-09 08:20:19 -05:00
parent 9306432a1b
commit 933acafaf3
89 changed files with 18 additions and 117 deletions

View File

@@ -0,0 +1,31 @@
-- Custom set module
require "set"
-- You pass an array in, and it gets converted to a set.
local states_needed = set.new({"mt", "wa", "or", "id", "nv", "ut", "ca", "az"})
local stations = {}
stations["kone"] = set.new({"id", "nv", "ut"})
stations["ktwo"] = set.new({"wa", "id", "mt"})
stations["kthree"] = set.new({"or", "nv", "ca"})
stations["kfour"] = set.new({"nv", "ut"})
stations["kfive"] = set.new({"ca", "az"})
local final_stations = set.new()
while next(states_needed) ~= nil do
local best_station = nil
local states_covered = set.new()
for station, states in pairs(stations) do
local covered = states_needed * states
if covered:len() > states_covered:len() then
best_station = station
states_covered = covered
end
end
states_needed = states_needed - states_covered
final_stations:add(best_station)
end
print(final_stations)

View File

@@ -0,0 +1,79 @@
set = {}
local mt = {__index = set}
function set.new(array)
local s = {}
if array ~= nil then
for _, value in pairs(array) do
s[value] = true
end
end
return setmetatable(s, mt)
end
function set:add(value)
if value ~= nil then
self[value] = true
end
return self
end
function set:remove(value)
if value ~= nil then
self[value] = nil
end
return self
end
function set:len()
local len = 0
for _ in pairs(self) do
len = len + 1
end
return len
end
function set.union(a, b)
local result = set.new()
for key in pairs(a) do
result[key] = true
end
for key in pairs(b) do
result[key] = true
end
return result
end
function set.difference(a, b)
local result = set.new()
for key in pairs(a) do
result[key] = true
end
for key in pairs(b) do
result[key] = nil
end
return result
end
function set.intersection(a, b)
local result = set.new()
for key in pairs(a) do
result[key] = b[key]
end
return result
end
function set.tostring(s)
local array = {}
for key in pairs(s) do
array[#array + 1] = tostring(key)
end
return "{" .. table.concat(array, ", ") .. "}"
end
mt.__add = set.union
mt.__sub = set.difference
mt.__mul = set.intersection
mt.__tostring = set.tostring
return set