From 7d7b3ee15db979d19133e54c59d340a5941452f0 Mon Sep 17 00:00:00 2001 From: mappu Date: Sun, 19 May 2024 18:10:39 +1200 Subject: [PATCH] initial commit --- countdown.sh | 25 ++++++++++++++++ solve.sh | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100755 countdown.sh create mode 100755 solve.sh diff --git a/countdown.sh b/countdown.sh new file mode 100755 index 0000000..4321466 --- /dev/null +++ b/countdown.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +set -eu + +randn() { + # 1-ARG inclusive + seq 1 $1 | shuf | head -n1 +} + +big() { + echo '10 25 50 75 100' | tr ' ' $'\n' | shuf | head -n1 +} + +small() { + seq 1 10 | shuf | head -n1 +} + +main() { + printf "Target: %03d\n" $(randn 999) + printf "Numbers: %d %d %d %d %d %d\n" \ + `big` `big` `small` `small` `small` `small` +} + +main "$@" + diff --git a/solve.sh b/solve.sh new file mode 100755 index 0000000..e764fc6 --- /dev/null +++ b/solve.sh @@ -0,0 +1,80 @@ +#!/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 "$@" +