CombinationGenerator.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/ADT/CombinationGenerator.h ------------------------*- C++ -*--===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// Combination generator.
  16. ///
  17. /// Example: given input {{0, 1}, {2}, {3, 4}} it will produce the following
  18. /// combinations: {0, 2, 3}, {0, 2, 4}, {1, 2, 3}, {1, 2, 4}.
  19. ///
  20. /// It is useful to think of input as vector-of-vectors, where the
  21. /// outer vector is the variable space, and inner vector is choice space.
  22. /// The number of choices for each variable can be different.
  23. ///
  24. /// As for implementation, it is useful to think of this as a weird number,
  25. /// where each digit (==variable) may have different base (==number of choices).
  26. /// Thus modelling of 'produce next combination' is exactly analogous to the
  27. /// incrementing of an number - increment lowest digit (pick next choice for the
  28. /// variable), and if it wrapped to the beginning then increment next digit.
  29. ///
  30. //===----------------------------------------------------------------------===//
  31. #ifndef LLVM_ADT_COMBINATIONGENERATOR_H
  32. #define LLVM_ADT_COMBINATIONGENERATOR_H
  33. #include "llvm/ADT/ArrayRef.h"
  34. #include "llvm/ADT/STLFunctionalExtras.h"
  35. #include "llvm/ADT/SmallVector.h"
  36. #include <cassert>
  37. #include <cstring>
  38. namespace llvm {
  39. template <typename choice_type, typename choices_storage_type,
  40. int variable_smallsize>
  41. class CombinationGenerator {
  42. template <typename T> struct WrappingIterator {
  43. using value_type = T;
  44. const ArrayRef<value_type> Range;
  45. typename decltype(Range)::const_iterator Position;
  46. // Rewind the tape, placing the position to again point at the beginning.
  47. void rewind() { Position = Range.begin(); }
  48. // Advance position forward, possibly wrapping to the beginning.
  49. // Returns whether the wrap happened.
  50. bool advance() {
  51. ++Position;
  52. bool Wrapped = Position == Range.end();
  53. if (Wrapped)
  54. rewind();
  55. return Wrapped;
  56. }
  57. // Get the value at which we are currently pointing.
  58. const value_type &operator*() const { return *Position; }
  59. WrappingIterator(ArrayRef<value_type> Range_) : Range(Range_) {
  60. assert(!Range.empty() && "The range must not be empty.");
  61. rewind();
  62. }
  63. };
  64. const ArrayRef<choices_storage_type> VariablesChoices;
  65. void performGeneration(
  66. const function_ref<bool(ArrayRef<choice_type>)> Callback) const {
  67. SmallVector<WrappingIterator<choice_type>, variable_smallsize>
  68. VariablesState;
  69. // 'increment' of the the whole VariablesState is defined identically to the
  70. // increment of a number: starting from the least significant element,
  71. // increment it, and if it wrapped, then propagate that carry by also
  72. // incrementing next (more significant) element.
  73. auto IncrementState =
  74. [](MutableArrayRef<WrappingIterator<choice_type>> VariablesState)
  75. -> bool {
  76. for (WrappingIterator<choice_type> &Variable :
  77. llvm::reverse(VariablesState)) {
  78. bool Wrapped = Variable.advance();
  79. if (!Wrapped)
  80. return false; // There you go, next combination is ready.
  81. // We have carry - increment more significant variable next..
  82. }
  83. return true; // MSB variable wrapped, no more unique combinations.
  84. };
  85. // Initialize the per-variable state to refer to the possible choices for
  86. // that variable.
  87. VariablesState.reserve(VariablesChoices.size());
  88. for (ArrayRef<choice_type> VC : VariablesChoices)
  89. VariablesState.emplace_back(VC);
  90. // Temporary buffer to store each combination before performing Callback.
  91. SmallVector<choice_type, variable_smallsize> CurrentCombination;
  92. CurrentCombination.resize(VariablesState.size());
  93. while (true) {
  94. // Gather the currently-selected variable choices into a vector.
  95. for (auto I : llvm::zip(VariablesState, CurrentCombination))
  96. std::get<1>(I) = *std::get<0>(I);
  97. // And pass the new combination into callback, as intended.
  98. if (/*Abort=*/Callback(CurrentCombination))
  99. return;
  100. // And tick the state to next combination, which will be unique.
  101. if (IncrementState(VariablesState))
  102. return; // All combinations produced.
  103. }
  104. };
  105. public:
  106. CombinationGenerator(ArrayRef<choices_storage_type> VariablesChoices_)
  107. : VariablesChoices(VariablesChoices_) {
  108. #ifndef NDEBUG
  109. assert(!VariablesChoices.empty() && "There should be some variables.");
  110. llvm::for_each(VariablesChoices, [](ArrayRef<choice_type> VariableChoices) {
  111. assert(!VariableChoices.empty() &&
  112. "There must always be some choice, at least a placeholder one.");
  113. });
  114. #endif
  115. }
  116. // How many combinations can we produce, max?
  117. // This is at most how many times the callback will be called.
  118. size_t numCombinations() const {
  119. size_t NumVariants = 1;
  120. for (ArrayRef<choice_type> VariableChoices : VariablesChoices)
  121. NumVariants *= VariableChoices.size();
  122. assert(NumVariants >= 1 &&
  123. "We should always end up producing at least one combination");
  124. return NumVariants;
  125. }
  126. // Actually perform exhaustive combination generation.
  127. // Each result will be passed into the callback.
  128. void generate(const function_ref<bool(ArrayRef<choice_type>)> Callback) {
  129. performGeneration(Callback);
  130. }
  131. };
  132. } // namespace llvm
  133. #endif
  134. #ifdef __GNUC__
  135. #pragma GCC diagnostic pop
  136. #endif