Poker hand analyser: Difference between revisions
Content deleted Content added
m {{out}} / Category:Cards |
→{{header|Ruby}}: change rank symbol |
||
Line 1,616:
attr_accessor :ordinal
attr_reader :suit, :face
SUITS = %i(♥ ♦ ♣ ♠)
FACES = %i(2 3 4 5 6 7 8 9 10 j q k a)
Line 1,624:
@ordinal = FACES.index(@face)
end
def <=> (other) #used for sorting
self.ordinal <=> other.ordinal
end
def to_s
end
private
def parse(str)
face, suit = str.chop.to_sym, str[-1].to_sym
raise
[face, suit]
end
end
class Hand
include Comparable
attr_reader :cards, :rank
RANKS = %i(
WHEEL_FACES = %i(2 3 4 5 a)
def initialize(str_of_cards)
@cards = str_of_cards.downcase.
grouped = @cards.group_by(&:face).values
@tiebreaker = grouped.sort_by {|ar| [ar.size, ar.first]}.reverse▼
@face_pattern = grouped.map(&:size).sort
@rank = categorize
@rank_num = RANKS.index(@rank)
end
def <=> (other) # used for sorting and comparing
self.compare_value <=> other.compare_value
end
def to_s
@cards.map(&:to_s).join(" ")
end
protected # accessible for Hands
def compare_value
[@rank_num, @tiebreaker]
end
private
def one_suit?
@cards.map(&:suit).uniq.size == 1
end
def consecutive?
sort.each_cons(2).all? {|c1,c2| c2.ordinal - c1.ordinal == 1 }
end
def sort
if @cards.sort.map(&:face) == WHEEL_FACES
@cards.detect {|c| c.face == :a}.ordinal = -1
end
Line 1,693 ⟶ 1,688:
def categorize
if consecutive?
else
when [1,1,1,
when [1,
when [1,
when [
when [
when [
when [5] then :'five-of-a-kind'
end
end
end
# Demo
test_hands = <<EOS
2♥ 5♥ 7♦ 8♣ 9♠
a♥ 2♦ 3♣ 4♣ 5♦
Line 1,725 ⟶ 1,721:
9♥ 10♥ q♥ k♥ j♣
2♥ 3♥ 4♥ 5♥ a♥
2♥ 2♥ 2♦ 3♣ 3♦
EOS
hands = test_hands.each_line.map{|line| Hand.new(line) }
puts "High to low"
hands.sort.reverse.each{|hand| puts "#{hand}\t #{hand.
puts
str = <<EOS
str = "joker 2♦ 2♠ k♠ q♦▼
joker j♥ q♥ k♥ A♥
joker
joker
joker
EOS
# Neither the Card nor the Hand class supports jokers
Line 1,755 ⟶ 1,754:
all_tries = cards_in_arrays.shift.product(*cards_in_arrays).map{|ar| Hand.new(ar.join" ")} #calculate the Whatshisname product
best = all_tries.max
puts "#{line.strip}: #{best.
end</lang>
{{out}}
<pre>
Line 1,790 ⟶ 1,789:
joker 2♦ 2♠ joker q♦: four-of-a-kind
</pre>
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
|