aboutsummaryrefslogtreecommitdiff
path: root/challenge-106/abigail/lua
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-04-01 14:32:11 +0200
committerAbigail <abigail@abigail.be>2021-04-01 14:32:11 +0200
commite807fc6f75dd661c7abf9ff73b1af7932d32a98d (patch)
tree6c1e04f31c12ada6734e301373c27b19533ec722 /challenge-106/abigail/lua
parentb96bc945b68514ba79e2c5a6f781d6e1cb63aa29 (diff)
downloadperlweeklychallenge-club-e807fc6f75dd661c7abf9ff73b1af7932d32a98d.tar.gz
perlweeklychallenge-club-e807fc6f75dd661c7abf9ff73b1af7932d32a98d.tar.bz2
perlweeklychallenge-club-e807fc6f75dd661c7abf9ff73b1af7932d32a98d.zip
Lua solution for week 106, part 2
Diffstat (limited to 'challenge-106/abigail/lua')
-rw-r--r--challenge-106/abigail/lua/ch-2.lua41
1 files changed, 41 insertions, 0 deletions
diff --git a/challenge-106/abigail/lua/ch-2.lua b/challenge-106/abigail/lua/ch-2.lua
new file mode 100644
index 0000000000..9ac554756d
--- /dev/null
+++ b/challenge-106/abigail/lua/ch-2.lua
@@ -0,0 +1,41 @@
+#!/opt/local/bin/lua
+
+--
+-- See ../README.md
+--
+
+--
+-- Run as: lua ch-2.lua < input-file
+--
+
+--
+-- For explaination of the method below, see ../README.md
+--
+
+function long_division (numerator, denominator)
+ local BASE = 10
+ local fraction = math . floor (numerator / denominator) .. "."
+ local position = fraction : len ()
+ local seen = {}
+
+ numerator = numerator % denominator
+
+ while (not seen [numerator]) do
+ if numerator == 0
+ then return (fraction)
+ end
+ seen [numerator] = position;
+ fraction = fraction .. math . floor (BASE * numerator / denominator)
+ numerator = BASE * numerator % denominator
+ position = position + 1
+ end
+
+ return (fraction : sub (1, seen [numerator]) .. '(' ..
+ fraction : sub (1 + seen [numerator]) .. ')')
+
+end
+
+for line in io . lines () do
+ local _, _, numerator, denominator = line : find ("(%d+)%s+(%d+)")
+ print (long_division (numerator, denominator))
+end