Skip to content

Instantly share code, notes, and snippets.

@TheIndifferent
Created February 21, 2020 19:59
Show Gist options
  • Save TheIndifferent/9537af5acff6edb16a8080ef03069ac5 to your computer and use it in GitHub Desktop.
Save TheIndifferent/9537af5acff6edb16a8080ef03069ac5 to your computer and use it in GitHub Desktop.
#!/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