aboutsummaryrefslogtreecommitdiff
path: root/challenge-115/abigail/lua
diff options
context:
space:
mode:
Diffstat (limited to 'challenge-115/abigail/lua')
-rw-r--r--challenge-115/abigail/lua/ch-1.lua64
-rw-r--r--challenge-115/abigail/lua/ch-2.lua59
2 files changed, 123 insertions, 0 deletions
diff --git a/challenge-115/abigail/lua/ch-1.lua b/challenge-115/abigail/lua/ch-1.lua
new file mode 100644
index 0000000000..650c2e1c1b
--- /dev/null
+++ b/challenge-115/abigail/lua/ch-1.lua
@@ -0,0 +1,64 @@
+#!/opt/local/bin/lua
+
+--
+-- See ../README.md
+--
+
+--
+-- Run as: lua ch-1.lua < input-file
+--
+
+for line in io . lines () do
+ local graph = {}
+ local nodes = {}
+ for s in line : gmatch ("%S+")
+ do local first = s : sub ( 1, 1)
+ local last = s : sub (-1, -1)
+ if graph [first] == nil
+ then graph [first] = {}
+ end
+ graph [first] [last] = 1
+ nodes [first] = 1
+ nodes [last] = 1
+ end
+
+ --
+ -- Make sure all entries exists, as lua doesn't autovivify
+ --
+ for node1 in pairs (nodes)
+ do for node2 in pairs (nodes)
+ do if graph [node1] == nil
+ then graph [node1] = {}
+ end
+ if graph [node1] [node2] == nil
+ then graph [node1] [node2] = 0
+ end
+ end
+ end
+
+ --
+ -- Calculate the transitive closure
+ --
+ for k in pairs (nodes)
+ do for i in pairs (nodes)
+ do for j in pairs (nodes)
+ do if graph [i] [j] == 0 and graph [k] [j] == 1 and
+ graph [i] [k] == 1
+ then graph [i] [j] = 1
+ end
+ end
+ end
+ end
+
+ --
+ -- We have a loop iff there is a node which is reachable from itself
+ --
+ local out = 0
+ for i in pairs (nodes)
+ do if graph [i] [i] == 1
+ then out = 1
+ end
+ end
+
+ print (out)
+end
diff --git a/challenge-115/abigail/lua/ch-2.lua b/challenge-115/abigail/lua/ch-2.lua
new file mode 100644
index 0000000000..4b92535d53
--- /dev/null
+++ b/challenge-115/abigail/lua/ch-2.lua
@@ -0,0 +1,59 @@
+#!/opt/local/bin/lua
+
+--
+-- See ../README.md
+--
+
+--
+-- Run as: lua ch-2.lua < input-file
+--
+
+local NR_OF_DIGITS = 10
+
+for line in io . lines () do
+
+ --
+ -- Process the input, count digits
+ --
+ local digits = {}
+ for i = 0, NR_OF_DIGITS - 1
+ do digits [i] = 0
+ end
+ for d in line : gmatch ("%d")
+ do d = tonumber (d)
+ digits [d] = digits [d] + 1
+ end
+
+ --
+ -- Find the lowest even digit
+ --
+ local last = -1
+ for i = NR_OF_DIGITS - 2, 0, -2
+ do if digits [i] > 0
+ then last = i
+ end
+ end
+
+ --
+ -- Skip if there is no even digit in the input
+ --
+ if last < 0
+ then goto end_loop
+ end
+
+ digits [last] = digits [last] - 1
+
+ --
+ -- Create output: digits from high to low
+ --
+ local out = ""
+ for i = NR_OF_DIGITS - 1, 0, -1
+ do for j = 1, digits [i]
+ do out = out .. tostring (i)
+ end
+ end
+
+ print (out .. tostring (last))
+
+ ::end_loop::
+end