HOG2
Combinations.h
Go to the documentation of this file.
1 //
2 // Combinations.h
3 //
4 // Created by Nathan Sturtevant on 11/9/18.
5 // Distributed with MIT License
6 //
7 
8 #ifndef Combinations_h
9 #define Combinations_h
10 
11 constexpr uint64_t ConstFactorial(int n)
12 {
13  return (n < 2)?1:(n*ConstFactorial(n-1));
14 }
15 
16 constexpr uint64_t ConstChooseHelper(int n, int k)
17 {
18  return (k > 0)?(n*ConstChooseHelper(n-1, k-1)):1;
19 
20 }
21 constexpr uint64_t ConstChoose(int n, int k)
22 {
23  return (2*k > n)?(ConstChooseHelper(n, n-k)/ConstFactorial(n-k)):(ConstChooseHelper(n, k)/ConstFactorial(k));
24 }
25 
26 template <int N>
27 class Combinations {
28 public:
29  uint64_t MaxRank(int k) const { return ConstChoose(N, k); }
30  uint64_t Rank(int *items, int k) const { return RankHelper(items, k, N, 0); }
31  void Unrank(uint64_t hash, int *items, int k) const { return UnrankHelper(hash, items, k, N, N); }
32 private:
33  uint64_t RankHelper(int *board, int count, int spaces, int offset) const
34  {
35  if (count == 0)
36  return 0;
37  if (board[0]-offset == 0)
38  return RankHelper(&board[1], count-1, spaces-1, offset+1);
39  uint64_t res = ConstChoose(spaces-1, count-1);
40  return res+RankHelper(board, count, spaces-1, offset+1);
41  }
42 
43  void UnrankHelper(uint64_t rank, int *board, int count, int spaces, int total) const
44  {
45  if (count == 0)
46  return;
47  uint64_t res = ConstChoose(spaces-1, count-1);
48  if (rank >= res)
49  UnrankHelper(rank-res, board, count, spaces-1, total);
50  else {
51  board[0] = total-spaces;
52  UnrankHelper(rank, &board[1], count-1, spaces-1, total);
53  }
54  }
55 
56 };
57 
58 
59 #endif /* Combinations_h */
Combinations::MaxRank
uint64_t MaxRank(int k) const
Definition: Combinations.h:29
Combinations::RankHelper
uint64_t RankHelper(int *board, int count, int spaces, int offset) const
Definition: Combinations.h:33
Combinations::UnrankHelper
void UnrankHelper(uint64_t rank, int *board, int count, int spaces, int total) const
Definition: Combinations.h:43
ConstChooseHelper
constexpr uint64_t ConstChooseHelper(int n, int k)
Definition: Combinations.h:16
Combinations
Definition: Combinations.h:27
Combinations::Rank
uint64_t Rank(int *items, int k) const
Definition: Combinations.h:30
ConstFactorial
constexpr uint64_t ConstFactorial(int n)
Definition: Combinations.h:11
ConstChoose
constexpr uint64_t ConstChoose(int n, int k)
Definition: Combinations.h:21
Combinations::Unrank
void Unrank(uint64_t hash, int *items, int k) const
Definition: Combinations.h:31