Skip to content

Commit 4c69182

Browse files
add deck shuffle with proper randomising
1 parent 7a3895f commit 4c69182

File tree

4 files changed

+25
-10
lines changed

4 files changed

+25
-10
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
.idea
1+
.idea/

README.md

Whitespace-only changes.

deck.go

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,25 @@
11
package main
22

3-
import "fmt"
3+
import (
4+
"fmt"
5+
"math/rand"
6+
"time"
7+
)
48

59
// Create a new type of 'deck'
610
// type deck is a slice of strings
7-
type deck [] string
11+
type deck []string
812

913
func newDeck() deck {
10-
cards := deck {}
11-
12-
cardSuits := [] string {
14+
cards := deck{}
15+
cardSuits := []string{
1316
"Spades",
1417
"Diamonds",
1518
"Hearts",
1619
"Clubs",
1720
}
1821

19-
cardValues := [] string {
22+
cardValues := []string{
2023
"Ace",
2124
"Two",
2225
"Three",
@@ -34,10 +37,9 @@ func newDeck() deck {
3437

3538
for _, suit := range cardSuits {
3639
for _, value := range cardValues {
37-
cards = append(cards, value + " of " + suit)
40+
cards = append(cards, value+" of "+suit)
3841
}
3942
}
40-
4143
return cards
4244
}
4345

@@ -46,3 +48,15 @@ func (d deck) print() {
4648
fmt.Println(i, card)
4749
}
4850
}
51+
52+
func (d deck) shuffle() {
53+
source := rand.NewSource(time.Now().UnixNano())
54+
r := rand.New(source)
55+
56+
for i := range d {
57+
newPosition := r.Intn(len(d) - 1)
58+
// One line index swap
59+
// x,y = y,x
60+
d[i], d[newPosition] = d[newPosition], d[i]
61+
}
62+
}

main.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@ package main
22

33
func main() {
44
cards := newDeck()
5+
cards.shuffle()
56
cards.print()
6-
}
7+
}

0 commit comments

Comments
 (0)