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

1 Answer

0 votes
package main

import (
    "fmt"
    "math/rand"
    "time"
)

/*
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:
    - slices of strings for the deck
    - rand.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
*/

func buildDeck() []string {
    ranks := []string{"2","3","4","5","6","7","8","9","10","J","Q","K","A"}
    suits := []string{"Clubs", "Diamonds", "Hearts", "Spades"}

    deck := make([]string, 0, 52)

    for _, suit := range suits {
        for _, rank := range ranks {
            deck = append(deck, rank+" of "+suit)
        }
    }

    return deck
}

func shuffleDeck(deck []string) {
    rand.Shuffle(len(deck), func(i, j int) {
        deck[i], deck[j] = deck[j], deck[i]
    })
}

func drawFive(deck []string, drawNumber int) []string {
    // Shuffle the remaining deck before this draw
    shuffleDeck(deck)

    fmt.Printf("Draw #%d:\n", drawNumber)
    for i := 0; i < 5; i++ {
        fmt.Println(" ", deck[i])
    }
    fmt.Println()

    // Remove drawn cards
    return deck[5:]
}

func main() {
    rand.Seed(time.Now().UnixNano())

    // Number of draws
    draws := 3

    deck := buildDeck()

    // Perform multiple draws (no duplicates)
    for drawIndex := 1; drawIndex <= draws; drawIndex++ {
        if len(deck) < 5 {
            fmt.Printf("Not enough cards left for draw #%d.\n", drawIndex)
            break
        }

        deck = drawFive(deck, drawIndex)
    }
}


/*
run:

Draw #1:
  K of Clubs
  7 of Clubs
  2 of Diamonds
  5 of Clubs
  A of Hearts

Draw #2:
  J of Diamonds
  4 of Diamonds
  J of Spades
  5 of Diamonds
  3 of Hearts

Draw #3:
  3 of Clubs
  A of Clubs
  Q of Diamonds
  Q of Clubs
  J of Hearts

*/

 



answered 4 hours ago by avibootz

Related questions

...