Bash Tape Equilibrium
tape_equilibrium() {
local -n _a="$1"
local _firstPart=0
local _secondPart=0
local _v
for _v in "${_a[@]}"; do _secondPart=$(( _secondPart + _v )); done
local _min=9223372036854775807
local _i
for ((_i = 0; _i < ${#_a[@]} - 1; _i++)); do
_firstPart=$(( _firstPart + _i ))
_secondPart=$(( _secondPart - _i ))
local _diff=$(( _firstPart - _secondPart ))
(( _diff < 0 )) && _diff=$(( -_diff ))
(( _diff < _min )) && _min=$_diff
done
echo "$_min"
}
This keeps left and right running sums and updates the smallest difference at each split point.
Bash Triangle
triangle() {
local -n _a="$1"
local -a _sorted=($(printf '%s\n' "${_a[@]}" | sort -n))
local _c=${#_sorted[@]}
if (( _c < 3 )); then
echo 0
return
fi
local _i
for ((_i = 0; _i < _c - 2; _i++)); do
if (( _sorted[_i] > 0 && _sorted[_i] > _sorted[_i+2] - _sorted[_i+1] )); then
echo 1
return
fi
done
echo 0
}
This sorts the values and checks nearby triples, because a valid triangle only needs one local match after sorting.