[2023][ruby][7.x] refactoring

main
Alpha Chen 12 months ago
parent 8b21d78e9a
commit ee07a6130e
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

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

Loading…
Cancel
Save