読者です 読者をやめる 読者になる 読者になる

Simple or trump(CodeEval)

簡易版大富豪の実装。
Scoreが80%ぐらいで、何かの考慮漏れがありそうなんだけど、よくわからないので一旦諦め。

CHALLENGE DESCRIPTION:

First playing cards were invented in Eastern Asia and then spread all over the world taking different forms and appearance. In India, playing cards were round, and they were called Ganjifa. In medieval Japan, there was a popular Uta-garuta game, in which shell mussels were used instead of playing cards.
In our game, we use playing cards that are more familiar nowadays. The rules are also simple: an ace beats a deuce (2) unless it is a trump deuce.

INPUT SAMPLE:

The first argument is a path to a file. Each line includes a test case which contains two playing cards and a trump suit. Cards and a trump suite are separated by a pipeline (|). The card deck includes thirteen ranks (from a deuce to an ace) of each of the four suits: clubs (♣), diamonds (♦), hearts (♥), and spades (♠). There are no Jokers.

AD 2H | H
KD KH | C
JH 10S | C

OUTPUT SAMPLE:

Your task is to print a card that wins. If there is no trump card, then the higher card wins. If the cards are equal, then print both cards.

2H
KD KH
JH

CONSTRAINTS:

  1. The card deck includes ranks from a deuce (2) to an ace, no Jokers.
  2. If the cards are equal, then print both cards.
  3. The number of test cases is 40.

My Code

#!/usr/bin/env ruby -w
class Card
  TRUMP_DUCE_RANK = 15
  SIGN_CARD_RANK = {
    "J" => 11,
    "Q" => 12,
    "K" => 13,
    "A" => 14
  }
  attr_reader :rank

  def initialize(card, trump)
    @card = card
    @trump = trump
    @rank = card_to_rank(card, trump)
  end

  def to_s
    @card
  end

  private
    def card_to_rank(card, trump)
      number = card[0...-1]
      rank = SIGN_CARD_RANK[number] || number.to_i
      rank = TRUMP_DUCE_RANK if rank == 2 && card[-1] == trump
      rank
    end
end

def game(cards, trump)
  x, y = cards.map { |card| Card.new(card, trump) }
  if x.rank > y.rank
    x.to_s
  elsif x.rank == y.rank
    "#{x} #{y}"
  else
    y.to_s
  end
end

ARGF.each_line do |line|
  cards_str, trump = line.chomp.split(" | ")
  cards = cards_str.split
  puts game(cards, trump)
end