How to perform multiple 5‑card draws from a shuffled 52‑card deck in Ruby

1 Answer

0 votes
# 
# A standard deck of 52 playing cards consists of four suits:
# spades (♠), hearts (♥), diamonds (♦), and clubs (♣).
#
# Each suit contains 13 ranks:
# Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King.
#
# Cards of spades and clubs are black, while hearts and diamonds are red.
#
# Color is informational only — it does not affect shuffling or random selection.
#

#
# This program performs multiple draws of 5 random cards from a 52‑card deck
# WITHOUT duplicates across draws.
#
# It uses:
# - Arrays for ranks, suits, and the deck
# - shuffle for efficient randomization (Fisher–Yates internally)
# - Functions for clean structure
#
# Algorithm:
# 1. Build a full deck (52 cards)
# 2. For each draw:
#    a. Shuffle the remaining deck
#    b. Draw 5 cards
#    c. Remove them from the deck
#

def build_deck
  ranks = %w[2 3 4 5 6 7 8 9 10 J Q K A]
  suits = %w[Clubs Diamonds Hearts Spades]

  deck = []

  suits.each do |suit|
    ranks.each do |rank|
      deck << "#{rank} of #{suit}"
    end
  end

  deck
end

def draw_five(deck, draw_number)
  # Shuffle the remaining deck before this draw
  deck.shuffle!

  puts "Draw ##{draw_number}:"
  deck.first(5).each do |card|
    puts "  #{card}"
  end
  puts

  # Remove drawn cards
  deck.shift(5)
end

def main
  # Number of draws
  number_of_draws = 3

  deck = build_deck

  # Perform multiple draws (no duplicates)
  (1..number_of_draws).each do |draw_index|
    if deck.length < 5
      puts "Not enough cards left for draw ##{draw_index}."
      break
    end

    draw_five(deck, draw_index)
  end
end

main


#
# run:
#
# Draw #1:
#   J of Hearts
#   J of Diamonds
#   6 of Clubs
#   8 of Hearts
#   4 of Clubs
# 
# Draw #2:
#   2 of Hearts
#   7 of Diamonds
#   3 of Spades
#   Q of Clubs
#   4 of Hearts
# 
# Draw #3:
#   9 of Hearts
#   4 of Diamonds
#   7 of Clubs
#   A of Diamonds
#   A of Clubs
#

 



answered 4 hours ago by avibootz

Related questions

...