ZonoOpt 2.5.0
Loading...
Searching...
No Matches
GenUtilities.hpp
Go to the documentation of this file.
1#pragma once
2
14#include <vector>
15#include <sstream>
16#include <iostream>
17
18namespace ZonoOpt::detail
19{
20 // generated by Gemini
21 template<typename T>
22 void combinations_util(const std::vector<T>& elements, const size_t k, const size_t start_index,
23 std::vector<T>& current_combination,
24 std::vector<std::vector<T>>& result)
25 {
26 // Base case: Combination is complete (size k reached)
27 if (current_combination.size() == k)
28 {
29 result.push_back(current_combination);
30 return;
31 }
32
33 // Recursive step: Iterate over available elements
34 for (size_t i = start_index; i < elements.size(); ++i)
35 {
36 // 🌟 Pruning optimization: stop if there aren't enough elements left to form a k-combination
37 if (elements.size() - i < k - current_combination.size())
38 {
39 return;
40 }
41
42 // 1. Include elements[i]
43 current_combination.push_back(elements[i]);
44
45 // 2. Recurse (start from i + 1 to prevent repeats)
46 combinations_util(elements, k, i + 1, current_combination, result);
47
48 // 3. Backtrack (remove element to try the next possibility)
49 current_combination.pop_back();
50 }
51 }
52
53 // generated by Gemini
54 template<typename T>
55 std::vector<std::vector<T>> get_combinations(const std::vector<T>& input_set, const size_t k)
56 {
57 if (k > input_set.size())
58 {
59 return {}; // Cannot choose k elements from a smaller set
60 }
61
62 // Copy set elements to a vector. std::set ensures they are already sorted.
63 std::vector<T> elements(input_set.begin(), input_set.end());
64
65 std::vector<std::vector<T>> result;
66 std::vector<T> current_combination;
67
68 // Start the recursive process from the first element (index 0)
69 combinations_util(elements, k, 0, current_combination, result);
70 return result;
71 }
72
73 inline void print_str(std::stringstream& ss)
74 {
75#ifdef IS_PYTHON_ENV
76 py::print(ss.str());
77#else
78 std::cout << ss.str() << std::endl;
79#endif
80 ss.str("");
81 }
82}