Golang : Create and shuffle deck of cards example




Problem:

You want to create a computer game like Strip Poker or you simply want to create a program that uses a deck of cards for studying gambling or probability. Instead of hand coding each card with text string into a map, you want to create the cards on the fly into a slice and want to shuffle the cards as well. How to do that?

Solution:

Create two arrays such as

 var suit = [4]string{"Hearts", "Diamonds", "Clubs", "Spades"}

and

 var face = [13]string{"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}

then combine the elements with for loops to create the initial deck of cards. You can create a separate function to shuffle the cards afterward.

Here you go!

 package main

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

 // let just stick to arrays instead of slice
 // because 4 x 13 is pretty standard for most decks....unless you want to include jokers.

 var suit = [4]string{"Hearts", "Diamonds", "Clubs", "Spades"}

 var face = [13]string{"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}

 const rows = 13
 const columns = 4
 const total = rows * columns

 // shuffle deck of cards
 func shuffleDeck(workDeck []string) []string {

 shuffled := make([]string, len(workDeck))

 rand.Seed(time.Now().UTC().UnixNano())
 perm := rand.Perm(len(workDeck))

 for i, v := range perm {
 shuffled[v] = workDeck[i]
 }

 return shuffled
 }

 func main() {

 var initDeck []string

 //initialize or populate our initial deck of cards
 //in sorted form
 for r := 0; r <= rows-1; r++ {
 for c := 0; c <= columns-1; c++ {
 tmp := face[r] + " of " + suit[c]
 initDeck = append(initDeck, tmp)

 }
 }

 // our new deck of cards is sorted !
 for k, v := range initDeck {
 fmt.Printf("%d %s\n", k, v)
 }

 fmt.Println("-----shuffling deck------")
 shuffledDeck := shuffleDeck(initDeck)

 // our new deck of cards is now shuffled !
 for k, v := range shuffledDeck {
 fmt.Printf("%d %s\n", k, v)
 }

 }

Output:

0 Ace of Hearts

1 Ace of Diamonds

2 Ace of Clubs

3 Ace of Spades

...

50 King of Clubs

51 King of Spades

-----shuffling deck------

0 Ace of Spades

1 Deuce of Clubs

2 Seven of Diamonds

3 Deuce of Diamonds

4 Queen of Clubs

5 Ten of Diamonds

6 Nine of Hearts

7 Deuce of Spades

...

49 Jack of Hearts

50 Ten of Spades

51 Six of Diamonds

Happy coding!

References:

https://en.wikipedia.org/wiki/Strip_poker (NSFW)

https://www.socketloop.com/tutorials/golang-shuffle-strings-array





By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


Advertisement