Implementation of Permutation, Combinations and PowerSet in C++ [duplicate]

Using STL: Permutation: using std::next_permutation template <typename T> void Permutation(std::vector<T> v) { std::sort(v.begin(), v.end()); do { std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, ” “)); std::cout << std::endl; } while (std::next_permutation(v.begin(), v.end())); } Combination: template <typename T> void Combination(const std::vector<T>& v, std::size_t count) { assert(count <= v.size()); std::vector<bool> bitset(v.size() – count, 0); bitset.resize(v.size(), 1); do { for (std::size_t i … Read more

Two arrays, where items in array x can be in array y but not vice versa, test all permutations

Use this for creating the power set of x: function power(x, y) { var r = [y || []], // an empty set/array as fallback l = 1; for (var i=0; i<x.length; l=1<<++i) // OK, l is just r[i].length, but this looks nicer 🙂 for (var j=0; j<l; j++) { r.push(r[j].slice(0)); // copy r[j].push(x[i]); } … Read more

Unordered combinations of all lengths

You could apply a sequence the length of x over the m argument of the combn() function. x <- c(“red”, “blue”, “black”) do.call(c, lapply(seq_along(x), combn, x = x, simplify = FALSE)) # [[1]] # [1] “red” # # [[2]] # [1] “blue” # # [[3]] # [1] “black” # # [[4]] # [1] “red” “blue” … Read more