-
-
Save symonty/61d35752a223c1bee1ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Darwin | |
extension Array { | |
mutating func shuffle() -> Array { | |
// this will sometimes crash (submitted bug #17127524) | |
self.sort { _,_ in arc4random_uniform(2) == 1 } | |
return self | |
} | |
mutating func removeAtIndexes( i:Int... ) { | |
var indexes = i | |
indexes.sort(>) | |
for i in indexes { removeAtIndex(i) } | |
} | |
} | |
class CardSet { | |
struct Card { | |
enum Suit:Int { | |
case Hearts, Diamonds, Clubs, Spades | |
} | |
enum Rank:Int { | |
case Two, Three, Four, Five, Six | |
case Seven, Eight, Nine, Ten | |
case Jack, Queen, King, Ace | |
} | |
let suit:Suit | |
let rank:Rank | |
} | |
var cards:[Card] | |
init() { cards = [] } | |
init( _ cards:[Card] ) { self.cards = cards } | |
var isEmpty:Bool { return cards.isEmpty } | |
} | |
class Deck:CardSet { | |
override init() { | |
var array = Array(0...52) | |
let indexes = array.shuffle() | |
super.init(indexes.map { index in | |
let suit = Card.Suit(rawValue: index % 4)! | |
let rank = Card.Rank(rawValue: index % 13)! | |
return Card(suit: suit, rank: rank) | |
}) | |
} | |
func drawCard() -> Card { return cards.removeLast() } | |
} | |
class Hand:CardSet { | |
var canPlay:Bool { | |
return cards.count >= 4 && (ranksMatch() || suitsMatch()) | |
} | |
func play() { | |
if ranksMatch() { cards.removeAtIndexes(3, 2, 1, 0) } | |
else if suitsMatch() { cards.removeAtIndexes(2, 1) } | |
} | |
func add( card:Card ) { cards.insert(card, atIndex: 0) } | |
func ranksMatch() -> Bool { return cards[0].rank == cards[3].rank } | |
func suitsMatch() -> Bool { return cards[1].suit == cards[2].suit } | |
} | |
struct Game { | |
var deck = Deck() | |
var hand = Hand() | |
func play() -> Bool { | |
while !deck.isEmpty { | |
hand.add( deck.drawCard() ) | |
while hand.canPlay { hand.play() } | |
} | |
return hand.isEmpty | |
} | |
} | |
let games = 1000 | |
var wins = 0 | |
for _ in 0...games { if Game().play() { wins++ } } | |
let winningPercentage = Double(wins) / Double(games) | |
println("Played \(games) games, \(wins) (\(winningPercentage)%) wins.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Xcode 6.2 compliant, I think?
Not sure what it is supposed to do but fixed the syntax changes.