Created
August 31, 2016 17:00
-
-
Save Chryus/241a856a1750f318e59387dcc83e8820 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#initialize a deck of cards and print out | |
#shuffle deck | |
class Deck | |
attr_reader :suits, :cards, :length | |
def initialize | |
@suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] | |
@cards = build | |
@length = 52 | |
end | |
def shuffle | |
# iterate over each card and swap it with a randomly select card | |
# each card has the same probability of landing in any given spot (1/52) | |
cards.each_with_index do |card, current_index| | |
new_index = random | |
cards[current_index], cards[new_index] = cards[new_index], cards[current_index] | |
end | |
cards | |
end | |
private | |
def random | |
rand(0...length) | |
end | |
def build | |
new_deck = [] | |
suits.each do |suit| | |
for card in (2..14) | |
case card | |
when 11 | |
new_deck << "Jack of #{suit}" | |
when 12 | |
new_deck << "Queen of #{suit}" | |
when 13 | |
new_deck << "King of #{suit}" | |
when 14 | |
new_deck << "Ace of #{suit}" | |
else 2..10 | |
new_deck << "#{card} of #{suit}" | |
end | |
end | |
end | |
new_deck | |
end | |
end | |
deck = Deck.new | |
puts deck.cards | |
puts deck.length | |
puts deck.shuffle | |
puts deck.length | |
describe Deck do | |
subject(:deck) { Deck.new } | |
it 'should initialize with an array of 52 cards' do | |
expect(subject.cards.class).to eq(Array) | |
expect(subject.cards.length).to eq(52) | |
end | |
it 'should start at card 2 for each new suit by increments of 13' do | |
expect(subject.cards[0]).to eq("2 of Clubs") | |
expect(subject.cards[13]).to eq("2 of Diamonds") | |
expect(subject.cards[26]).to eq("2 of Hearts") | |
expect(subject.cards[39]).to eq("2 of Spades") | |
end | |
it 'should end at Ace card for each suit by increments of 13 after the first suit' do | |
expect(subject.cards[12]).to eq("Ace of Clubs") | |
expect(subject.cards[25]).to eq("Ace of Diamonds") | |
expect(subject.cards[38]).to eq("Ace of Hearts") | |
expect(subject.cards[51]).to eq("Ace of Spades") | |
end | |
it 'should have swapped some cards after shuffle' do | |
original_deck = subject.cards.dup | |
subject.shuffle | |
expect(original_deck == subject.cards).to be(false) | |
end | |
it 'should have the same number of cards after shuffle' do | |
expect(subject.shuffle.length).to eq(52) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment