Skip to content

Instantly share code, notes, and snippets.

@worthlesscog
Created May 3, 2012 19:32
Show Gist options
  • Save worthlesscog/2588514 to your computer and use it in GitHub Desktop.
Save worthlesscog/2588514 to your computer and use it in GitHub Desktop.
Card deck with Shuffle
import scala.util.Random
trait Shuffle {
var cards: List[Card]
lazy val random = new Random
def shuffle {
def shuffle(cards: List[Card], size: Int, pile: List[Card] = Nil): List[Card] = {
if (size > 0) {
val card = cards(random.nextInt(size))
val (bef, aft) = cards.span(_ != card)
shuffle(bef ::: aft.tail, size - 1, card :: pile)
} else pile
}
cards = shuffle(cards, cards.size)
}
}
class Deck extends Shuffle {
var cards = for (r ← Rank.values.toList; s ← Suit.values) yield r of s
def next = {
if (!cards.isEmpty) {
val card = cards.head
cards = cards.tail
Some(card)
} else None
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment