-
-
Save kevinlebrun/5910429 to your computer and use it in GitHub Desktop.
Prime Factors Kata in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
TEST=${TEST:+'test'} | |
function prime_factors_of { | |
local number=$1 | |
for (( divisor=2; number > 1; divisor++ )); do | |
for (( ; number % divisor == 0; number /= divisor )); do | |
prime_factors=("${prime_factors[@]}" $divisor) | |
done | |
done | |
echo "${prime_factors[@]}" | |
} | |
function assert_prime_factors_of { | |
read result < <(prime_factors_of $1) | |
if [ "$result" = "$2" ]; then | |
echo -n '.' | |
else | |
echo -n 'F' | |
echo "Failure asserting that $2 are factors of $1" >&2 | |
echo " -> $2 is expected, $result is returned" >&2 | |
fi | |
} | |
function suite { | |
assert_prime_factors_of 1 | |
assert_prime_factors_of 2 2 | |
assert_prime_factors_of 3 3 | |
assert_prime_factors_of 4 "2 2" | |
assert_prime_factors_of 5 5 | |
assert_prime_factors_of 6 "2 3" | |
assert_prime_factors_of 7 7 | |
assert_prime_factors_of 8 "2 2 2" | |
assert_prime_factors_of 9 "3 3" | |
assert_prime_factors_of $((2 * 3 * 5 * 5 * 7 * 13)) "2 3 5 5 7 13" | |
} | |
function report_failing_tests { | |
echo -n $1 | tr -d "F" | wc -c | xargs -Ixxx echo -n "xxx passing test(s)" | |
} | |
function report_passing_tests { | |
echo -n $1 | tr -d "." | wc -c | xargs -Ixxx echo -n "xxx failing test(s)" | |
} | |
function report { | |
echo $1 | |
echo "$(report_passing_tests $1), $(report_failing_tests $1)" | |
} | |
case $TEST in | |
'test') | |
echo 'Testing...' | |
read suite_result < <(suite) | |
report $suite_result | |
;; | |
*) | |
echo 'Running...' | |
prime_factors_of $1 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can either use the program with
./pf 2013
or run the tests withTEST=1 ./pf
.