From aa4f9e49e6aaa1ca25bcd2999c98b62f23ff5eaf Mon Sep 17 00:00:00 2001 From: Abigail Date: Wed, 31 Mar 2021 15:06:48 +0200 Subject: Bash solution for week 106, part 2 --- challenge-106/abigail/README.md | 1 + challenge-106/abigail/bash/ch-2.sh | 43 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 challenge-106/abigail/bash/ch-2.sh diff --git a/challenge-106/abigail/README.md b/challenge-106/abigail/README.md index 2f9f8e7880..6c1a682ffc 100644 --- a/challenge-106/abigail/README.md +++ b/challenge-106/abigail/README.md @@ -93,6 +93,7 @@ Wikipedia](https://en.wikipedia.org/wiki/Repeating_decimal). ### Solutions * [AWK](perl/ch-2.awk) +* [Bash](bash/ch-2.sh) * [Perl](perl/ch-2.pl) ### Blog diff --git a/challenge-106/abigail/bash/ch-2.sh b/challenge-106/abigail/bash/ch-2.sh new file mode 100644 index 0000000000..77f38b81c3 --- /dev/null +++ b/challenge-106/abigail/bash/ch-2.sh @@ -0,0 +1,43 @@ +#!/bin/sh + +# +# See ../README.md +# + +# +# Run as: bash ch-2.sh < input-file +# + +set -f + +declare fraction + +function long_division () { + declare numerator=$1 + declare denominator=$2 + declare BASE=10 + fraction=$((numerator / denominator)). + declare position=${#fraction} + declare -a seen + + ((numerator %= denominator)) + + while ((!seen[numerator])) + do if ((numerator == 0)) + then return + fi + seen[$numerator]=$position + fraction=$fraction$((BASE * numerator / denominator)) + ((numerator = BASE * numerator % denominator)) + ((position ++)) + done + fraction=${fraction::${seen[$numerator]}}\(${fraction:${seen[$numerator]}}\) +} + + +while read numerator denominator +do long_division $numerator $denominator + echo $fraction +done + + -- cgit