aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-02-18 01:06:54 +0100
committerAbigail <abigail@abigail.be>2021-02-18 01:13:52 +0100
commit5d34a6625bbb1fb1b92181dddec2459480157f53 (patch)
treee0f6e67507b0164bb7c929294abb8a17de5acbd1
parent46a34ac4699c3981c6325652ff34a9087635d70e (diff)
downloadperlweeklychallenge-club-5d34a6625bbb1fb1b92181dddec2459480157f53.tar.gz
perlweeklychallenge-club-5d34a6625bbb1fb1b92181dddec2459480157f53.tar.bz2
perlweeklychallenge-club-5d34a6625bbb1fb1b92181dddec2459480157f53.zip
Lua solution for week 100, part 1
-rw-r--r--challenge-100/abigail/README.md1
-rw-r--r--challenge-100/abigail/lua/ch-1.lua56
2 files changed, 57 insertions, 0 deletions
diff --git a/challenge-100/abigail/README.md b/challenge-100/abigail/README.md
index d4f0bcee6b..c3d1134d80 100644
--- a/challenge-100/abigail/README.md
+++ b/challenge-100/abigail/README.md
@@ -22,6 +22,7 @@ Output: 07:15 pm or 07:15pm
* [Bash](bash/ch-1.sh)
* [Befunge-93](befunge-93/ch-1.bf93)
* [C](c/ch-1.c)
+* [Lua](lua/ch-1.lua)
* [Perl](perl/ch-1.pl)
### Blog
diff --git a/challenge-100/abigail/lua/ch-1.lua b/challenge-100/abigail/lua/ch-1.lua
new file mode 100644
index 0000000000..6e0f3a721a
--- /dev/null
+++ b/challenge-100/abigail/lua/ch-1.lua
@@ -0,0 +1,56 @@
+#!/opt/local/bin/lua
+
+--
+-- See ../README.md
+--
+
+--
+-- Run as: lua ch-1.lua < input-file
+--
+
+for line in io . lines () do
+ --
+ -- Parse input
+ --
+ local _, _, hour, minute, ampm = line : find ("(%d+):(%d+)%s*([ap]?)m?")
+
+ --
+ -- We need an explicite case to numbers
+ --
+ hour = tonumber (hour)
+ minute = tonumber (minute)
+
+ --
+ -- Find out what the new AM/PM marker should be:
+ -- - If the current marker is AM or PM, the new one is empty.
+ -- - Else, if the hour is 12 or higher, it's PM
+ -- - Else, it's AM
+ --
+ local new_ampm = ""
+ if ampm == ""
+ then if hour >= 12
+ then new_ampm = "pm"
+ else new_ampm = "am"
+ end
+ end
+
+ --
+ -- Calculate the new hours
+ -- - If AM, an hour of 12 becomes 0, and we leave the rest as is
+ -- - If PM, an hour of 12 stays 12, else, we add 12 to the hour
+ -- - If no AM/PM, subtract 12 if the hour is larger than 12;
+ -- add 12 if the hour is 0
+ --
+ hour = hour % 12
+ if ampm == "" and hour == 0
+ then hour = 12
+ end
+ if ampm == "p"
+ then hour = hour + 12
+ end
+
+ --
+ -- Print the results
+ --
+ print (string . format ("%02d:%02d%s", hour, minute, new_ampm))
+end