aboutsummaryrefslogtreecommitdiff
path: root/challenge-115/abigail/lua/ch-2.lua
diff options
context:
space:
mode:
authorLuis Mochan <mochan@fis.unam.mx>2021-06-05 00:10:09 -0500
committerLuis Mochan <mochan@fis.unam.mx>2021-06-05 00:10:09 -0500
commitc9c7142570ee4f82f6c0998e6ecfae6f032fe463 (patch)
tree4aa5bf856c3e2d832ca8374cbff82d7527ef76aa /challenge-115/abigail/lua/ch-2.lua
parentc18fb21257876cc864357fa7a2237995c1f6b169 (diff)
parent373a97f7ee737cbd8d3e8d87a96b6ae0dec388b5 (diff)
downloadperlweeklychallenge-club-c9c7142570ee4f82f6c0998e6ecfae6f032fe463.tar.gz
perlweeklychallenge-club-c9c7142570ee4f82f6c0998e6ecfae6f032fe463.tar.bz2
perlweeklychallenge-club-c9c7142570ee4f82f6c0998e6ecfae6f032fe463.zip
Merge branch 'master' of github.com:manwar/perlweeklychallenge-club into challenges
Diffstat (limited to 'challenge-115/abigail/lua/ch-2.lua')
-rw-r--r--challenge-115/abigail/lua/ch-2.lua59
1 files changed, 59 insertions, 0 deletions
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