Skip to content

Instantly share code, notes, and snippets.

@yaegashi
Last active August 29, 2015 14:23
Show Gist options
  • Save yaegashi/57065723166e3a72b79e to your computer and use it in GitHub Desktop.
Save yaegashi/57065723166e3a72b79e to your computer and use it in GitHub Desktop.
Card hand generator & matcher http://unix.stackexchange.com/a/211717/116972
#!/bin/bash
# This version conforms to Bash 3.2.53 on OS X.
stab=('\e[0;31;47m ♦' '\e[0;31;47m ♥' '\e[0;30;47m ♠' '\e[0;30;47m ♣')
ntab=(2 3 4 5 6 7 8 9 10 J Q K A)
match() {
for i; do
printf " ${stab[$((i/13))]}${ntab[$((i%13))]}\e[0m"
done
printf "\n"
suits=(0 0 0 0)
nums=(0 0 0 0 0 0 0 0 0 0 0 0 0)
same2=()
same3=()
same4=()
flush=-1
straight=-1
conseq=0
for i; do
((suits[i/13]++))
((nums[i%13]++))
done
for ((i=0; i<4; i++)); do
((suits[i]==5)) && flush=$i
done
for ((i=0; i<13; i++)); do
case ${nums[$i]} in
2) same2+=($i) ;;
3) same3+=($i) ;;
4) same4+=($i) ;;
esac
if ((i>0)); then
conseq=$((nums[i]>0?(nums[i-1]>0?conseq+1:1):0))
else
conseq=$((nums[i]>0?1:0))
fi
((conseq==5)) && straight=$i
done
if ((${#same4[*]}>0)); then
echo "FOUR OF A KIND - ${ntab[${same4[0]}]}"
elif ((${#same3[*]}>0)); then
if ((${#same2}>0)); then
echo "FULL HOUSE - ${ntab[${same3[0]}]} ${ntab[${same2[0]}]}"
else
echo "THREE OF A KIND - ${ntab[${same3[0]}]}"
fi
elif ((${#same2[*]}>1)); then
echo "TWO PAIR - ${ntab[${same2[1]}]} ${ntab[${same2[0]}]}"
elif ((${#same2[*]}>0)); then
echo "ONE PAIR - ${ntab[${same2[0]}]}"
elif ((straight>=0)); then
if ((flush>=0)); then
if ((straight==12)); then
echo "ROYAL FLUSH"
else
echo "STRAIGHT FLUSH"
fi
else
echo "STRAIGHT"
fi
elif ((flush>=0)); then
echo "FLUSH"
else
echo "NO PAIR"
fi
}
# Tests
match 14 45 0 11 49 # NO PAIR
match 51 13 39 9 50 # ONE PAIR
match 34 21 1 11 50 # TWO PAIR
match 8 3 21 22 34 # THREE OF A KIND
match 51 24 36 9 21 # STRAIGHT
match 1 3 5 7 9 # FLUSH
match 5 18 31 15 28 # FULL HOUSE
match 10 9 22 35 48 # FOUR OF A KIND
match 1 2 3 4 5 # STRAIGHT FLUSH
match 12 11 10 9 8 # ROYAL FLUSH
# Random draw
#match $(shuf -e -n 5 {0..51})
shuf=({0..51})
cards=()
for i in 0 1 2 3 4; do
j=$((RANDOM%${#shuf[*]}))
cards+=(${shuf[$j]})
unset shuf[$j]
done
match "${cards[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment