-
Notifications
You must be signed in to change notification settings - Fork 0
/
war.go
82 lines (72 loc) · 1.22 KB
/
war.go
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
package main
import (
"flag"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/ImJasonH/cards"
)
var games = flag.Int64("n", 100, "Number of games to play")
func main() {
flag.Parse()
p1wins := int64(0)
var wg sync.WaitGroup
for i := int64(0); i < *games; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if War().p1wins {
atomic.AddInt64(&p1wins, int64(1))
}
}()
}
wg.Wait()
fmt.Println(p1wins, *games-p1wins)
}
type Result struct {
p1wins bool
d time.Duration
turns, wars int
}
func War() Result {
start := time.Now()
d := cards.NewDeck()
d.Shuffle()
p1, p2 := d.Cut()
turn := 0
wars := 0
var pile Pile
for !p1.Empty() && !p2.Empty() {
if len(p1)+len(p2)+len(pile.Deck) != 52 {
panic("lost cards")
}
c1, c2 := *p1.Top(), *p2.Top()
pile.Add(c1, c2)
pile.Shuffle()
switch {
case c1 > c2:
p1.Add(pile.All()...)
case c2 > c1:
p2.Add(pile.All()...)
case c1 == c2:
wars++
pile.Add(p1.TopN(3)...)
pile.Add(p2.TopN(3)...)
pile.Shuffle()
}
turn++
}
return Result{
p1wins: p2.Empty(),
d: time.Since(start),
turns: turn,
wars: wars,
}
}
type Pile struct {
cards.Deck
}
func (p *Pile) All() []cards.Card {
return p.TopN(len(p.Deck))
}