Created
February 21, 2020 19:59
-
-
Save TheIndifferent/9537af5acff6edb16a8080ef03069ac5 to your computer and use it in GitHub Desktop.
Bash solution for Rain Water kata: https://gist.github.com/knifeofdreams/b6ffe05679e77a7789a6b8921b75e152
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 | |
function max_number() { | |
echo $(( $1 > $2 ? $1 : $2 )) | |
} | |
function trim_line_breaks() { | |
tr -d '\n' | |
} | |
function reverse_map() { | |
tail -r | |
} | |
function remove_elevation() { | |
sed 's/X//g' | |
} | |
function count_water() { | |
wc -c | |
} | |
function fill_in_water_after_peaks() { | |
local max_elevation=0 | |
for elevation in $@ | |
do | |
max_elevation="$( max_number $elevation $max_elevation )" | |
[[ $elevation -gt 0 ]] && echo -n "$( yes X | head -$elevation | trim_line_breaks )" | |
[[ $elevation -lt $max_elevation ]] && echo -n "$( yes W | head -$(( max_elevation - elevation )) | trim_line_breaks )" | |
echo '' | |
done | |
} | |
function reduce_water_before_peaks() { | |
local max_elevation=0 | |
while read -r line | |
do | |
local elevation="$( echo $line | sed 's/W//g' | trim_line_breaks | wc -c )" | |
max_elevation="$( max_number $elevation $max_elevation )" | |
[[ $max_elevation -gt 0 ]] && echo -n "$line" | head -c $max_elevation | |
echo '' | |
done | |
} | |
fill_in_water_after_peaks $@ \ | |
| reverse_map \ | |
| reduce_water_before_peaks \ | |
| remove_elevation \ | |
| trim_line_breaks \ | |
| count_water |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment