Add Permutations method to Cards
parent
4adab71872
commit
b0126631ff
|
@ -1,4 +1,5 @@
|
|||
0.1.2:
|
||||
- Add Permutations method to Cards
|
||||
- Rename library from cards to joker
|
||||
|
||||
0.1.1:
|
||||
|
|
26
cards.go
26
cards.go
|
@ -141,6 +141,32 @@ func (c Cards) Reversed() Cards {
|
|||
return cc
|
||||
}
|
||||
|
||||
// Permutations returns all permutations of the supplied cards.
|
||||
func (c Cards) Permutations() []Cards {
|
||||
var permute func(Cards, int)
|
||||
var res []Cards
|
||||
permute = func(c Cards, n int) {
|
||||
if n == 1 {
|
||||
res = append(res, c.Copy())
|
||||
} else {
|
||||
for i := 0; i < n; i++ {
|
||||
permute(c, n-1)
|
||||
if n%2 == 1 {
|
||||
tmp := c[i]
|
||||
c[i] = c[n-1]
|
||||
c[n-1] = tmp
|
||||
} else {
|
||||
tmp := c[0]
|
||||
c[0] = c[n-1]
|
||||
c[n-1] = tmp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
permute(c, len(c))
|
||||
return res
|
||||
}
|
||||
|
||||
// Low returns the lowest valued card.
|
||||
func (c Cards) Low() Card {
|
||||
if len(c) == 0 {
|
||||
|
|
|
@ -73,6 +73,11 @@ func TestCards(t *testing.T) {
|
|||
t.Errorf("failed to sort cards: expected %s, got %s", c.Sorted, sorted)
|
||||
}
|
||||
|
||||
permutations := c.Cards.Permutations()
|
||||
if len(permutations) != factorial(len(c.Cards)) {
|
||||
t.Errorf("failed to generate permutations: expected %d, got %d: %s", factorial(len(c.Cards)), len(permutations), permutations)
|
||||
}
|
||||
|
||||
low := c.Cards.Low()
|
||||
if !low.Equal(c.Low) {
|
||||
t.Errorf("failed to get low card: expected %s, got %s", c.Low, low)
|
||||
|
@ -92,3 +97,10 @@ func BenchmarkCardsSort(b *testing.B) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func factorial(i int) int {
|
||||
if i <= 1 {
|
||||
return 1
|
||||
}
|
||||
return i * factorial(i-1)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue