ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# binaryphile's solution

## to Grains in the Bash Track

Published at Sep 15 2018 · 0 comments
Instructions
Test suite
Solution

#### Note:

This exercise has changed since this solution was written.

Calculate the number of grains of wheat on a chessboard given that the number on each square doubles.

There once was a wise servant who saved the life of a prince. The king promised to pay whatever the servant could dream up. Knowing that the king loved chess, the servant told the king he would like to have grains of wheat. One grain on the first square of a chess board. Two grains on the next. Four on the third, and so on.

There are 64 squares on a chessboard.

Write code that shows:

• how many grains were on each square, and
• the total number of grains

## For bonus points

Did you get the tests passing and the code clean? If you want to, these are some additional things you could try:

• Optimize for speed.

Then please share your thoughts in a comment on the submission. Did this experiment make the code better? Worse? Did you learn anything from it?

Run the tests with:

``````bats grains_test.sh
``````

After the first test(s) pass, continue by commenting out or removing the `skip` annotations prepending other tests.

## Source

JavaRanch Cattle Drive, exercise 6 http://www.javaranch.com/grains.jsp

## External utilities

`Bash` is a language to write scripts that works closely with various system utilities, like `sed`, `awk`, `date` and even other programming languages, like `Python`. This track does not restrict the usage of these utilities, and as long as your solution is portable between systems and does not require installing third party applications, feel free to use them to solve the exercise.

For an extra challenge, if you would like to have a better understanding of the language, try to re-implement the solution in pure `Bash`, without using any external tools.

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### grains_test.sh

``````#!/usr/bin/env bash

@test "1" {
#skip
run bash grains.sh 1
[ "\$status" -eq 0 ]
[ "\$output" == "1" ]
}

@test "2" {
skip
run bash grains.sh 2
[ "\$status" -eq 0 ]
[ "\$output" == "2" ]
}

@test "3" {
skip
run bash grains.sh 3
[ "\$status" -eq 0 ]
[ "\$output" == "4" ]
}

@test "4" {
skip
run bash grains.sh 4
[ "\$status" -eq 0 ]
[ "\$output" == "8" ]
}

@test "16" {
skip
run bash grains.sh 16
[ "\$status" -eq 0 ]
[ "\$output" == "32768" ]
}

@test "32" {
skip
run bash grains.sh 32
[ "\$status" -eq 0 ]
[ "\$output" == "2147483648" ]
}

@test "64" {
skip
run bash grains.sh 64
[ "\$status" -eq 0 ]
[ "\$output" == "9223372036854775808" ]
}

@test "square 0 raises an exception" {
skip
run bash grains.sh 0
[ "\$status" -eq 1 ]
[ "\$output" == "Error: invalid input" ]
}

@test "negative square raises an exception" {
skip
run bash grains.sh -1
[ "\$status" -eq 1 ]
[ "\$output" == "Error: invalid input" ]
}

@test "square greater than 64 raises an exception" {
skip
run bash grains.sh 65
[ "\$status" -eq 1 ]
[ "\$output" == "Error: invalid input" ]
}

@test "returns the total number of grains on the board" {
skip
run bash grains.sh total
[ "\$status" -eq 0 ]
[ "\$output" == "18446744073709551615" ]
}``````
``````#!/usr/bin/env bash

# http://www.binaryphile.com/bash/2018/07/26/approach-bash-like-a-developer-part-1-intro.html

IFS=\$'\037'
set -o noglob
shopt -s expand_aliases
alias noerror?='! (( \${err__:-} )) || (exit \$err__)'
alias raise='{ err__=\$?; ! read -rd "" __; return ;} <<<'

powers_of_2=( 1 )
sum_of_powers_of_2=( 1 )

get () {
local name_=\${1:-__}
local indent_

indent_=\${!name_%%[^[:space:]]*}
printf -v \$name_ %s \${!name_#\$indent_}
printf -v \$name_ %s \${!name_//\$'\n'\$indent_/\$'\n'}
}

get Usage <<'END'
Calculate the grains on a given chessboard square, starting at 1

Usage:  grains.sh NUMBER|total

The first square of the chessboard has a single grain, and each subsequent
square doubles the last.

NUMBER is the chessboard square, up to 64.

"total" instead totals all of the grains on all of the squares.
END

main () {
local -i i

case \$1 in
total ) sum_powers_of_2 63;;
* )
i=\$1-1
(( i < 64 )) || die "Error: invalid input"
power_of_2 \$i
;;
esac
echo \$__
noerror?
}

contains? () {
local item=\$1; shift

[[ "\$IFS\$*\$IFS" == *"\$IFS\$item\$IFS"* ]]
}

die () {
local rc=\$?

present? \${1:-} && echo \$1
exit \$rc
}

power_of_2 () {
local i=\$1
local rc

(( i >= 0 )) || raise "Error: invalid input"
(( i == 0 )) && {
__=1
return
}
case \${powers_of_2[i-1]:-} in
''  ) power_of_2 \$(( i - 1 )) ;;
*   ) __=\${powers_of_2[i-1]}  ;;
esac
__=\$(( 2 * __ ))
__=\${__#-}
powers_of_2[i]=\$__
! (( i >= 63 ))
case \$? in
0 ) (( sum_of_powers_of_2[i] = sum_of_powers_of_2[i-1] + __ ))        ;;
* ) sum_of_powers_of_2[i]=\$(bc <<<"\${sum_of_powers_of_2[i-1]} + \$__") ;;
esac
}

present? () {
[[ -n \${1:-} ]]
}

sourced? () {
[[ \${FUNCNAME[1]} == source ]]
}

strict_mode () {
case \$1 in
on  )
set -o errexit
set -o nounset
set -o pipefail
;;
off )
set +o errexit
set +o nounset
set +o pipefail
;;
esac
}

sum_powers_of_2 () {
power_of_2 \$1
noerror? || raise \$__
__=\${sum_of_powers_of_2[\$1]}
}

sourced? && return
strict_mode on

(( \$# > 0 )) || die \$'Error: argument required\n\n'\$Usage
contains? --help \$@ && die \$Usage
(( \$# < 2 )) || die \$'Error: wrong number of arguments\n\n'\$Usage
main \$@``````