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

Convert a map of lists into a list of maps

You can first iterate through map entries and represent list elements as Map<String,Integer> and get a stream of lists of maps, and then reduce this stream to a single list. Try it online! Map<String, List<Integer>> mapOfLists = new LinkedHashMap<>(); mapOfLists.put(“a”, List.of(1, 2, 3)); mapOfLists.put(“b”, List.of(4, 5, 6)); mapOfLists.put(“c”, List.of(7)); List<Map<String, Integer>> listOfMaps = mapOfLists.entrySet().stream() // … Read more

get all combinations for a string

This is a recursive solution that I think is very easy to understand. var tree = function(leafs) { var branches = []; if (leafs.length == 1) return leafs; for (var k in leafs) { var leaf = leafs[k]; tree(leafs.join(”).replace(leaf, ”).split(”)).concat(“”).map(function(subtree) { branches.push([leaf].concat(subtree)); }); } return branches; }; console.log(tree(“abc”.split(”)).map(function(str) { return str.join(”) }))

How to Generate Combinations of Elements of a List in .NET 4.0

Code in C# that produces list of combinations as arrays of k elements: public static class ListExtensions { public static IEnumerable<T[]> Combinations<T>(this IEnumerable<T> elements, int k) { List<T[]> result = new List<T[]>(); if (k == 0) { // single combination: empty set result.Add(new T[0]); } else { int current = 1; foreach (T element in … Read more