From fa33a7bdf75a9171ad09f70d71feefee69c7d3c2 Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Thu, 14 Dec 2023 13:47:28 +0000 Subject: [PATCH] Create dependencies exercise --- 19_dependencies.lua | 105 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 19_dependencies.lua diff --git a/19_dependencies.lua b/19_dependencies.lua new file mode 100644 index 0000000..ce72051 --- /dev/null +++ b/19_dependencies.lua @@ -0,0 +1,105 @@ +-- Write a function to generate a valid order for a number of jobs +-- that depend upon each other. Your input is a jobs table; each key +-- is a job number, with its the values being a list jobs it depends +-- on. You may assume that there are no circular dependencies. +-- +-- Return a list of job numbers, so that performing the jobs in that +-- order ensures that all jobs are exactly once, and all dependencies +-- of a job are done before prior to it. +-- +-- Solution -------------------------------------------------------------------- +function schedule(jobs) + -- Your implementation here +end + +-- Tests ----------------------------------------------------------------------- + +local luaunit = require("luaunit.luaunit") + +local function keys(t) + local results = {} + for key, _ in pairs(t) do table.insert(results, key) end + return results +end + +local function contains(list, target) + for _, item in ipairs(list) do if item == target then return true end end + return false +end + +local function deep_copy(original) + local copy = {} + if type(original) == "table" then + for key, value in pairs(original) do + local key_copy = deep_copy(key) + local value_copy = deep_copy(value) + copy[key_copy] = value_copy + end + else + copy = original + end + return copy +end + +local function assert_valid(order, jobs) + local done = {} + for _, job in ipairs(order) do + for _, dependency in ipairs(jobs[job]) do + luaunit.assertTrue(contains(done, dependency)) + end + table.insert(done, job) + end +end + +local function test_case(jobs) + local order = schedule(deep_copy(jobs)) + luaunit.assertItemsEquals(order, keys(jobs)) + assert_valid(order, jobs) +end + +function test_sequential_dependencies() + local jobs = {[1] = {2}, [2] = {3}, [3] = {}} + test_case(jobs) +end + +function test_converging_dependencies() + local jobs = { + [1] = {5}, + [2] = {5}, + [3] = {6}, + [4] = {6}, + [5] = {7}, + [6] = {7}, + [7] = {}, + } + test_case(jobs) +end + +function test_diverging_dependencies() + local jobs = { + [1] = {2, 3}, + [2] = {4, 5}, + [3] = {6, 7}, + [4] = {}, + [5] = {}, + [6] = {}, + [7] = {} + } + test_case(jobs) +end + +function test_compound_dependencies() + local jobs = { + [1] = {2, 3, 4}, + [2] = {5, 6}, + [3] = {7}, + [4] = {7}, + [5] = {}, + [6] = {8}, + [7] = {8}, + [8] = {} + } + test_case(jobs) +end + +os.exit(luaunit.LuaUnit.run())