countdown-bash/solve.sh

81 lines
1.4 KiB
Bash
Executable File

#!/bin/bash
set -eu
main() {
local targ="$1"
shift
local vals="$@"
#echo "solving for $targ using $vals"
for v in $vals ; do
if [[ $v == $targ ]] ; then
echo won
return 0
fi
done
if [[ $# < 2 ]] ; then
#echo "out of options"
return 1
fi
declare -i i
declare -i j
declare -i k
for (( i=1 ; i <= $# ; i++ )) ; do
for (( j=$i ; j <= $# ; j++ )) ; do
if [[ $i == $j ]] ; then
continue
fi
declare -i iv=${!i}
declare -i jv=${!j}
local others=''
for (( k=1 ; k <= $# ; k++ )) ; do
if [[ $i == $k || $j == $k ]] ; then
continue
fi
local kv=${!k}
others="$others $kv"
done
if main $targ $others $(($iv + $jv)) ; then
echo $iv + $jv = $(($iv + $jv))
return 0
fi
if main $targ $others $(($jv - $iv)) ; then
echo $jv - $iv = $(($jv - $iv))
return 0
fi
if main $targ $others $(($iv - $jv)) ; then
echo $iv - $jv = $(($iv - $jv))
return 0
fi
if main $targ $others $(($iv * $jv)) ; then
echo $iv x $jv = $(($iv * $jv))
return 0
fi
if [[ $jv != 0 && $(( $iv % $jv )) == 0 ]] && \
main $targ $others $(($iv / $jv)) ; then
echo $iv / $jv = $(($iv / $jv))
return 0
fi
if [[ $iv != 0 && $(( $jv % $iv )) == 0 ]] && \
main $targ $others $(($jv / $iv)) ; then
echo $jv / $iv = $(($jv / $iv))
return 0
fi
done
done
#echo "no solution"
return 1
}
main "$@"