#!/usr/bin/env tclsh8.6 namespace import ::tcl::mathop::* array set cardmap {2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 T 10 J 11 Q 12 K 13 A 14} while {[gets stdin line] >= 0} { lassign [split $line { }] hand bid set cards {} foreach card [split $hand {}] { lappend cards $cardmap($card) } lappend hands $cards lappend bids $bid } # For simplicity of ranking the hands, let's assign a "score" to each hand. # Each card's individual value fits in a hex digit, so we'll work in hex. # A score is dominated by the hand type ("two pair" etc.), so that has to # be the highest digit. Then there are 5 hex digits after that, one for # each card's value. proc score {hand} { set score 0 # Get the individual card digits first. foreach card $hand { set score [expr {($score << 4) | $card}] } # Now determine type. Easiest if the values are sorted first. lassign [lsort -integer $hand] a b c d e if {$a == $b && $b == $c && $c == $d && $d == $e} { # Five of a kind. return [| $score 0x600000] } if { ($a == $b && $b == $c && $c == $d) || ($b == $c && $c == $d && $d == $e) } { # Four of a kind. return [| $score 0x500000] } if { ($a == $b && $b == $c && $d == $e) || ($a == $b && $c == $d && $d == $e) } { # Full house. return [| $score 0x400000] } if { ($a == $b && $b == $c) || ($b == $c && $c == $d) || ($c == $d && $d == $e) } { # Three of a kind. return [| $score 0x300000] } if { ($a == $b && $c == $d) || ($a == $b && $d == $e) || ($b == $c && $d == $e) } { # Two pair. return [| $score 0x200000] } if { $a == $b || $b == $c || $c == $d || $d == $e } { # One pair. return [| $score 0x100000] } # High card only. return $score } # Build a list of (score, bid) pairs for sorting. for {set i 0} {$i < [llength $hands]} {incr i} { lappend pairs [list [score [lindex $hands $i]] [lindex $bids $i]] } set total 0 set rank 0 foreach pair [lsort -integer -index 0 $pairs] { incr rank incr total [* $rank [lindex $pair 1]] } puts $total