MCPcopy Create free account
hub / github.com/KaisenAmin/c_std / algorithm_next_permutation

Function algorithm_next_permutation

algorithm/algorithm.c:1101–1135  ·  view source on GitHub ↗

* @brief Generates the next lexicographical permutation of a range. * * This function rearranges the elements in the range `[first, last)` into the next lexicographical * permutation, as determined by the comparison function `comp`. If such a permutation is not possible, * the range is rearranged into the smallest lexicographical order (sorted in ascending order). * * @param first Pointer to

Source from the content-addressed store, hash-verified

1099 * @return `true` if the next permutation was generated, `false` if the range was reset to the smallest permutation.
1100 */
1101bool algorithm_next_permutation(void *first, void *last, size_t size, CompareFuncBool comp) {
1102 ALGORITHM_LOG("[algorithm_next_permutation] Info: Generating next permutation.");
1103 if (first == last) {
1104 ALGORITHM_LOG("[algorithm_next_permutation] Warning: Empty range, returning false.");
1105 return false;
1106 }
1107
1108 char *i = (char *)last - size;
1109 while (i != (char *)first) {
1110 char *j = i;
1111 i -= size;
1112
1113 if (comp(i, j)) {
1114 char *k = (char *)last - size;
1115 while (!comp(i, k)) {
1116 k -= size;
1117 }
1118
1119 ALGORITHM_LOG("[algorithm_next_permutation] Info: Swapping elements.");
1120 swap(i, k, size);
1121 reverse(j, last, size);
1122
1123 ALGORITHM_LOG("[algorithm_next_permutation] Success: Next permutation generated.");
1124 return true;
1125 }
1126
1127 if (i == (char *)first) {
1128 ALGORITHM_LOG("[algorithm_next_permutation] Info: Resetting to smallest permutation.");
1129 reverse(first, last, size);
1130 return false;
1131 }
1132 }
1133
1134 return false;
1135}
1136
1137
1138/**

Callers

nothing calls this directly

Calls 2

swapFunction · 0.85
reverseFunction · 0.85

Tested by

no test coverage detected