Skip to content

Instantly share code, notes, and snippets.

@epinaud
Created July 31, 2014 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epinaud/7921885ae26ae2914f7b to your computer and use it in GitHub Desktop.
Save epinaud/7921885ae26ae2914f7b to your computer and use it in GitHub Desktop.
My solution to Swift Ninja Final Challenge
enum Suit {
case Clubs, Diamonds, Hearts, Spades
}
enum Rank {
case Jack, Queen, King, Ace
case Num(Int)
}
struct Card {
let suit: Suit
let rank: Rank
}
func countHand(cards: [Card], calc: ((Card, Card) -> Int)? = nil) -> Int
{
return
!calc ?
// No calc closure defined (first call to countHand). Create closure and recall countHand with it!
countHand(cards, { (c1:Card, c2:Card) -> Int in
switch (c1.rank, c2.rank, c1.suit, c2.suit) {
case (_, Rank.Num(let internalRank),Suit.Hearts, _) where internalRank % 2 == 1:
return 2 * internalRank
case (Rank.Num(5), Rank.Ace, Suit.Diamonds, _):
return 100
default:
return 0
}}) :
// Calc closure defined. Just call calc + recursive countHand with cards array without first card
(cards.count < 2 ?
0 :
calc!(cards[0], cards[1]) + countHand(Array<Card>(dropFirst(cards)), calc: calc))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment