Skip to content

Instantly share code, notes, and snippets.

@fabienhinault
Last active December 18, 2022 16:46
Show Gist options
  • Save fabienhinault/a87ac5d167b2fea85b1018b9fa404d9f to your computer and use it in GitHub Desktop.
Save fabienhinault/a87ac5d167b2fea85b1018b9fa404d9f to your computer and use it in GitHub Desktop.
#!/bin/bash
readarray N < <(seq 0 100)
N[0]='_'
N[1]='_'
for ((prime=2; prime<=100; prime++))
do
if [[ N[$prime] != '_' ]]
then
for ((iTest=((prime + 1)); iTest<=100; iTest++))
do
if ((iTest % prime == 0 ))
then
N[$iTest]='_'
fi
done
fi
done
PRIMES=()
for prime in ${N[@]}
do
if [[ $prime != '_' ]]
then
PRIMES+=($prime)
fi
done
RANGE=32768
readarray A < <(seq 100)
function bidivides {
(( $1 % $2 == 0 || $2 % $1 == 0 ))
}
function get_candidates {
candidates=()
local last=$1
for n in ${A[@]}
do
if [[ $n != '_' ]] && bidivides $last $n
then
candidates+=("$n")
fi
done
}
function let_player_play_again {
while [ -z "$next" ] || ! bidivides $1 $next || [[ ${A[$((next - 1))]} == '_' ]]
do
echo ☹
echo 💻 $last
echo ${A[@]}
read -p '🚹 ' next
done
A[$((next - 1))]='_'
echo ${A[@]}
}
function let_player_play_first {
local last=$1
read -p '🚹 ' next
if [ -z $next ]
then
return 0
fi
let_player_play_again $1
}
function let_player_play {
local last=$1
read -p '🚹 ' next
let_player_play_again $1
}
function containsElement {
local e match="$1"
shift
for e; do [[ "$e" == "$match" ]] && return 0; done
return 1
}
function choose_next_1 {
for (( iprime=${#PRIMES[@]} - 1 ; iprime>=0 ; iprime-- ))
do
local prime=${PRIMES[iprime]}
if containsElement "$prime" ${A[@]}
then
next=$prime
return 0
fi
done
choose_next
}
function choose_next {
if [[ 1 == ${#candidates[@]} ]]
then
next=${candidates[0]}
else
for (( icandidate=${#candidates[@]} - 1 ; icandidate>=2 ; icandidate-- ))
do
if (( $RANDOM < $RANGE / 2 ))
then
next=${candidates[icandidate]}
return 0
fi
done
next=${candidates[1]}
fi
}
function play {
get_candidates $1
if [[ ${#candidates[@]} == 0 ]]
then
echo "Bravo, vous avez gagné !"
exit 0
else
if [[ 1 == $1 ]]
then
choose_next_1
else
choose_next
fi
A[$((next - 1))]='_'
echo 💻 $next
echo ${A[@]}
get_candidates $next
if [[ ${#candidates[@]} == 0 ]]
then
echo "J'ai gagné !"
exit 0
fi
fi
}
last=2
echo ${A[@]}
let_player_play_first $last
if [ -n "$next" ]
then
last=$next
fi
while [ -n $last ]
do
play $last
last=$next
let_player_play $last
last=$next
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment