How to pick 5 random cards from a 52‑card deck in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

'
' 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 picks 5 random cards from a standard 52‑card deck.
'
' It uses:
' - List(Of String) to store the deck
' - Fisher–Yates shuffle for efficient randomization
' - Random for high‑quality randomness
'
' Algorithm:
' 1. Build the deck (52 strings).
' 2. Shuffle using Fisher–Yates.
' 3. Print the first 5 cards.
'

Module RandomCards

    ' Build a full 52‑card deck
    Function BuildDeck() As List(Of String)
        Dim ranks() As String = {
            "2","3","4","5","6","7","8","9","10","J","Q","K","A"
        }

        Dim suits() As String = {
            "Clubs", "Diamonds", "Hearts", "Spades"
        }

        Dim deck As New List(Of String)(52)

        ' Combine each rank with each suit → 52 unique cards
        For Each suit In suits
            For Each rank In ranks
                deck.Add(rank & " of " & suit)
            Next
        Next

        Return deck
    End Function

    ' Shuffle the deck using Fisher–Yates
    Sub ShuffleDeck(deck As List(Of String))
        Dim rng As New Random()

        For i As Integer = deck.Count - 1 To 1 Step -1
            Dim j As Integer = rng.Next(i + 1)

            Dim temp As String = deck(i)
            deck(i) = deck(j)
            deck(j) = temp
        Next
    End Sub

    Sub Main()
        ' Step 1: Build the deck
        Dim deck As List(Of String) = BuildDeck()

        ' Step 2: Shuffle the deck
        ShuffleDeck(deck)

        ' Step 3: Draw the first 5 cards
        Console.WriteLine("Your 5 random cards:")
        For i As Integer = 0 To 4
            Console.WriteLine(deck(i))
        Next
    End Sub

End Module


'
' run:
'
' Your 5 random cards:
' 4 of Clubs
' A of Spades
' A of Hearts
' 3 of Diamonds
' A of Clubs
'

 



answered 1 day ago by avibootz
...