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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use rand::*;
use super::*;
#[test]
fn test_shuffle() {
let loop_count = 50;
let mut top_matches = 0;
let mut bottom_matches = 0;
for _ in 0..loop_count {
let mut d = Deck::new();
let t1 = d.top_card().unwrap();
let b1 = d.bottom_card().unwrap();
d.shuffle();
let t2 = d.top_card().unwrap();
let b2 = d.bottom_card().unwrap();
if t1 == t2 {
top_matches += 1;
}
if b1 == b2 {
bottom_matches += 1;
}
}
println!(
"top card matched {} times, bottom card matched {} times",
top_matches, bottom_matches
);
assert!(top_matches < loop_count);
assert!(bottom_matches < loop_count);
}
fn sort_suit_ascending_rank(cards: &mut [Card]) {
cards.sort_by(|a, b| a.cmp_suit_then_rank(b));
}
fn sort_suit_descending_rank(cards: &mut [Card]) {
cards.sort_by(|a, b| a.cmp_suit_then_desc_rank(b));
}
fn sort_descending_rank_suit(cards: &mut [Card]) {
cards.sort_by(|a, b| a.cmp_desc_rank_then_suit(b));
}
pub fn cards_of_rank(cards: &[Card], rank: Rank) -> Vec<Card> {
cards.iter().filter(|c| c.rank == rank).cloned().collect()
}
pub fn cards_of_suit(cards: &[Card], suit: Suit) -> Vec<Card> {
cards.iter().filter(|c| c.suit == suit).cloned().collect()
}
pub fn shuffle(cards: &mut [Card]) {
let mut rng = thread_rng();
let l = cards.len();
for n in 0..l {
let i = rng.gen_range(0, l - n);
cards.swap(i, l - n - 1);
}
}
pub trait Cards {
fn cards(&self) -> &[Card];
fn mut_cards(&mut self) -> &mut [Card];
fn shuffle(&mut self) {
shuffle(self.mut_cards());
}
fn sort_suit_ascending_rank(&mut self) {
sort_suit_ascending_rank(self.mut_cards());
}
fn sort_suit_descending_rank(&mut self) {
sort_suit_descending_rank(self.mut_cards());
}
fn sort_descending_rank_suit(&mut self) {
sort_descending_rank_suit(self.mut_cards());
}
}