# Golang : Create and shuffle deck of cards example

Tags :

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

...

50 King of Clubs

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

1 Deuce of Clubs

2 Seven of Diamonds

3 Deuce of Diamonds

4 Queen of Clubs

5 Ten of Diamonds

6 Nine of Hearts

...

49 Jack of Hearts

51 Six of Diamonds

Happy coding!

References:

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

Tags :