Created
April 29, 2025 11:56
-
-
Save bruteforceboy/b787d9636e8617d411f244ffe43dc704 to your computer and use it in GitHub Desktop.
nPr_iterative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <unordered_set> | |
#include <vector> | |
template <typename T> | |
std::vector<std::vector<T>> permute(std::vector<T> vec, int r) { | |
using PermTy = std::pair<std::unordered_set<int>, std::vector<T>>; | |
std::vector<PermTy> permutations{{}}; | |
while (r-- > 0) { | |
std::vector<PermTy> npermutations; | |
for (int i = 0; i < static_cast<int>(vec.size()); ++i) | |
for (auto [perm_set, perm_vec] : permutations) | |
if (!perm_set.count(i)) | |
perm_set.emplace(i), perm_vec.emplace_back(vec[i]), | |
npermutations.emplace_back(perm_set, perm_vec); | |
permutations = std::move(npermutations); | |
} | |
std::vector<std::vector<T>> ret; | |
for (auto &&[_, perm] : permutations) | |
ret.push_back(perm); | |
return ret; | |
} | |
int main() { | |
for (auto &perm : permute<std::string>({"how", "are", "you"}, 2)) { | |
for (auto &v : perm) | |
std::cout << v << " "; | |
std::cout << "\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment