-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeck.go
More file actions
76 lines (62 loc) · 1.33 KB
/
deck.go
File metadata and controls
76 lines (62 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package deck
import (
"math/rand"
"sort"
"time"
)
type Deck []Card
func New(opts ...func([]Card) []Card) Deck {
var cards []Card
for _, s := range suits {
for r := minRank; r <= maxRank; r++ {
cards = append(cards, Card{Suit: s, Rank: r})
}
}
for _, o := range opts {
cards = o(cards)
}
return cards
}
func Sort(less func(cards []Card) func(i, j int) bool) func([]Card) []Card {
return func(cards []Card) []Card {
sort.Slice(cards, less(cards))
return cards
}
}
func DefaultSort(cards []Card) []Card {
sort.Slice(cards, Less(cards))
return cards
}
// Shuffle the cards using Fisher–Yates algorithm.
func Shuffle(cards []Card) []Card {
r := rand.New(rand.NewSource(time.Now().Unix()))
for i := len(cards) - 1; i > 0; i-- {
j := r.Intn(i + 1)
cards[i], cards[j] = cards[j], cards[i]
}
return cards
}
func Jokers(n int) func([]Card) []Card {
return func(cards []Card) []Card {
for i := 0; i < n; i++ {
cards = append(cards, Card{Rank: Rank(i), Suit: Joker})
}
return cards
}
}
func Filter(f func(Card) bool) func([]Card) []Card {
return func(cards []Card) []Card {
var res []Card
for _, c := range cards {
if f(c) {
res = append(res, c)
}
}
return res
}
}
func Less(cards []Card) func(i, j int) bool {
return func(i, j int) bool {
return absRank(cards[i]) < absRank(cards[j])
}
}