Skip to main content
9 of 9
re-added the `THREE` counter increment `ct++` – was lost in the edits somewhere/sometime
Peter.O
  • 33.7k
  • 32
  • 120
  • 167
printf '%s\n' {♠,♣,♢,♡}$'\t'{{2..10},J,K,Q,A} | shuf -n5 |
  gawk 'BEGIN{ split(",Twos,Threes,Fours,Fives,Sixes,Sevens,Eights,Nines,Tens",vt,","); vt["J"]="Jacks"; vt["Q"]="Queens"; vt["K"]="Kings"; vt["A"]="Aces"; } # values-text
        { c[$2]++; printf("%s %s", $1, $2(NR==5?"\n":"\t")) }
        END{ for(i in c){
                 if( c[i]==2 ){ print "PAIR:  " vt[i]; cp++ }  
                 if( c[i]==3 ){ print "THREE: " vt[i]; ct++ }
                 if( c[i]==4 ){ print "FOUR:  " vt[i] } }
             if( cp==2  ) { print "TWO PAIRS" }
             if( cp&&ct ) { print "FULL HOUSE" } }'

Example output:

♡ Q    ♣ A    ♢ A    ♢ Q    ♡ 2 
PAIR:  Aces
PAIR:  Queens
TWO PAIRS

Here is the same thing done entirely by awk, except for the method of seeding awk's rand(), by using bash's $RANDOM passed to awk via the -v option. The output is identical to the above.

gawk -v seed=$RANDOM '
  BEGIN{srand(seed) 
        split("♠♣♢♡",s,"")  # suit: 1-4 
        split("A,2,3,4,5,6,7,8,9,10,J,Q,K",v,",")  # values: 1-13
        split(",Twos,Threes,Fours,Fives,Sixes,Sevens,Eights,Nines,Tens",vt,","); vt["A"]="Aces"; vt["J"]="Jacks"; vt["Q"]="Queens"; vt["K"]="Kings"; # values-text
        for(es in s){ for(ev in v){ sv[i++]=s[es]" "v[ev] }}; # 0-51
        imax=4; for(i=0;i<=imax;i++){              # pick 5 cards at random from array `v`
          rix=int(rand()*(52-i))+i                 # ranges from 0-51 to 4-51, as per `i`
          tmp=sv[i]; sv[i]=sv[rix]; sv[rix]=tmp    # swap ramdom value to front of array, as per `i` 
          split(sv[i],fv," "); c[fv[2]]++          # increment face-value counts  
          printf("%s", sv[i](i==imax?"\n":"\t"))   # print the full hand in incremets
        }
        for(i in c){
            if( c[i]==2 ){ print "PAIR:  " vt[i]; cp++ }  
            if( c[i]==3 ){ print "THREE: " vt[i]; ct++ }
            if( c[i]==4 ){ print "FOUR:  " vt[i] } }
        if( cp==2  ) { print "TWO PAIRS" }
        if( cp&&ct ) { print "FULL HOUSE" }}'
Peter.O
  • 33.7k
  • 32
  • 120
  • 167