Codehire Cup 2013 Solutions: Preliminary (Round 1)

A solution in Ruby to the Codehire Cup Preliminary (Round 1) problem in the second Codehire Cup held across Australia in June and July 2013.

In June and July 2013, Codehire held the second Codehire Cup across Australia. As last year, the contest featured some relatively simple coding problems. Contestants could choose to use C/C++, C#, Java, JavaScript, PHP, Python, or Ruby to submit solutions through a web-based interface.

Contestants were ranked according to the time taken to complete the problem, as well as by an assessment of their approach and coding style by a panel of judges.

The Problem

The Codehire Cup Preliminary (Round 1) problem read:

Summary

Calculate the card’s “inverse”.

A deck of playing cards has four suits: Hearts, Spades, Clubs and Diamonds. Cards within each suit are numbered from 2–9 with four additional cards being Jack, Queen, King and Ace.

For this exercise we will treat the Ace card as being a replacement for 1 with all other cards taking numbers through to 13. So each suit can be represented numerically as:

A  2  3  4  5  6  7  8  9  10  J   Q   K
1  2  3  4  5  6  7  8  9  10  11  12  13

We define the “inverse” of a card as being the inverse of its suit and the inverse of its number.

Inverses

The inverse of the card number is defined as:

Inverse(x) = 14 - x

We arbitrarily define the suit inverses as:

Suit          Inverse
Hearts     => Spades
Diamonds   => Clubs
Clubs      => Diamonds
Spades     => Hearts

Examples

Queen of Hearts would have the inverse 2 of Spades.

7 of Clubs would have the inverse of 7 of Diamonds.

Input and Output

You are given a card of the form:

<suit><number or face>

For example:

H7 => 7 of Hearts
SK => King of Spades

Challenge

Find the inverse of the given card and write to output in the same format.

The Solution

The simplest solution is to create an array of all of the suits and of all of the “numbers” of the card, and, for a given suit and “number”, select the suit and “number” at the opposite end of the relevant array.

suits = %w(H D C S)
cards = %w(A 2 3 4 5 6 7 8 9 10 J Q K)

suit = input[0]
card = input[1..-1]

inv_suit = suits[-suits.index(suit)-1]
inv_card = cards[-cards.index(card)-1]

output << inv_suit + inv_card

The solution assumes well-formed input.

Another Solution

As for last year’s Practice Challenge, we can squeeze the solution into the fewest number of characters possible to get a short, but not particularly elegant, solution. My solution in Ruby is 106 characters.

output<<(s=%w(H D C S))[-s.index(input[0])-1]+(c=%w(A 2 3 4 5 6 7 8 9 10 J Q K))[-c.index(input[1..-1])-1]

More Codehire Cup 2013 Solutions

Codehire Cup 2012 Solutions

Tags: Codehire Cup, coding contests