|
|
|
@ -8,24 +8,27 @@ HAND_STRENGTH = [
|
|
|
|
|
[1, 1, 1, 1, 1], # high card
|
|
|
|
|
].reverse.each.with_index.to_h { [_1, _2] }
|
|
|
|
|
|
|
|
|
|
module PartOne
|
|
|
|
|
CARD_STRENGTH = ((?2..?9).to_a + %w[ T J Q K A ]).each.with_index.to_h
|
|
|
|
|
class PartOne
|
|
|
|
|
CARD_RANK = ((?2..?9).to_a + %w[ T J Q K A ]).each.with_index.to_h
|
|
|
|
|
|
|
|
|
|
def self.strength(cards)
|
|
|
|
|
def strength(cards)
|
|
|
|
|
tally = cards.tally
|
|
|
|
|
strengths = [
|
|
|
|
|
HAND_STRENGTH.fetch(tally.values.sort),
|
|
|
|
|
*cards.map { CARD_STRENGTH.fetch(_1) },
|
|
|
|
|
self.hand_type(tally),
|
|
|
|
|
*cards.map { CARD_RANK.fetch(_1) },
|
|
|
|
|
]
|
|
|
|
|
strengths.map { (?a.ord + _1).chr }.join
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def hand_type(tally)
|
|
|
|
|
HAND_STRENGTH.fetch(tally.values.sort)
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
module PartTwo
|
|
|
|
|
CARD_STRENGTH = ([?J] + (?2..?9).to_a + %w[ T Q K A ]).each.with_index.to_h
|
|
|
|
|
class PartTwo < PartOne
|
|
|
|
|
CARD_RANK = ([?J] + (?2..?9).to_a + %w[ T Q K A ]).each.with_index.to_h
|
|
|
|
|
|
|
|
|
|
def self.strength(cards)
|
|
|
|
|
tally = cards.tally
|
|
|
|
|
def hand_type(tally)
|
|
|
|
|
jokers = tally.delete(?J) || 0
|
|
|
|
|
counts = tally.values.sort
|
|
|
|
|
if counts.empty?
|
|
|
|
@ -33,17 +36,20 @@ module PartTwo
|
|
|
|
|
else
|
|
|
|
|
counts[-1] += jokers
|
|
|
|
|
end
|
|
|
|
|
[
|
|
|
|
|
HAND_STRENGTH.fetch(counts),
|
|
|
|
|
*cards.map { CARD_STRENGTH.fetch(_1) },
|
|
|
|
|
]
|
|
|
|
|
HAND_STRENGTH.fetch(counts)
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
hands = ARGF.read.scan(/(\w+)\s+(\d+)/).to_h { [_1.chars, _2.to_i ] }
|
|
|
|
|
|
|
|
|
|
part_one = PartOne.new
|
|
|
|
|
p hands
|
|
|
|
|
.sort_by {|(hand,_)| part_one.strength(hand) }
|
|
|
|
|
.map.with_index {|(_,bid),i| bid * (i+1) }
|
|
|
|
|
.sum
|
|
|
|
|
|
|
|
|
|
part_two = PartTwo.new
|
|
|
|
|
p hands
|
|
|
|
|
# .sort_by {|(hand,_)| PartOne::strength(hand) }
|
|
|
|
|
.sort_by {|(hand,_)| PartTwo::strength(hand) }
|
|
|
|
|
.sort_by {|(hand,_)| part_two.strength(hand) }
|
|
|
|
|
.map.with_index {|(_,bid),i| bid * (i+1) }
|
|
|
|
|
.sum
|
|
|
|
|