Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Solution to Ray Wenderlich's Swift Ninja challenge
// Solution to ultimate Swift Nija challenge
// http://www.raywenderlich.com/77845/swift-ninja-part-2
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
}
// ---- Implementation ----
extension Int {
func isOdd() -> Bool {
return (self % 2 == 1)
}
}
struct CardCount {
let previous:Card
let sum:Int
}
func reduceFunc(upto:CardCount, card:Card) -> CardCount {
let previousCard = upto.previous
switch(card.rank, previousCard.suit, previousCard.rank) {
case (Rank.Ace, Suit.Diamonds, Rank.Num(5)):
return CardCount(previous:card, sum:upto.sum + 100)
case (Rank.Num(let num), Suit.Hearts, _) where num.isOdd():
return CardCount(previous: card, sum: upto.sum + num * 2)
default:
return CardCount(previous: card, sum: upto.sum)
}
}
func countHand(cards:[Card]) -> Int {
let tail = dropFirst(cards)
return tail.reduce(CardCount(previous: cards.first!,sum: 0), combine: reduceFunc).sum
}
// ==== Test ====
countHand([
Card(suit:Suit.Hearts, rank:Rank.Num(10)),
Card(suit:Suit.Hearts, rank:Rank.Num(6)),
Card(suit:Suit.Diamonds, rank:Rank.Num(5)),
Card(suit:Suit.Clubs, rank:Rank.Ace),
Card(suit:Suit.Diamonds, rank:Rank.Jack)
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment