Creating all possible k combinations of n items in C++

From Rosetta code #include <algorithm> #include <iostream> #include <string> void comb(int N, int K) { std::string bitmask(K, 1); // K leading 1’s bitmask.resize(N, 0); // N-K trailing 0’s // print integers and permute bitmask do { for (int i = 0; i < N; ++i) // [0..N-1] integers { if (bitmask[i]) std::cout << ” ” … Read more

Combinatoric ‘N choose R’ in java math?

The Formula It’s actually very easy to compute N choose K without even computing factorials. We know that the formula for (N choose K) is: N! ——– (N-K)!K! Therefore, the formula for (N choose K+1) is: N! N! N! N! (N-K) —————- = ————— = ——————– = ——– x —– (N-(K+1))!(K+1)! (N-K-1)! (K+1)! (N-K)!/(N-K) K!(K+1) … Read more

Cartesian product of a dictionary of lists

Ok, thanks @dfan for telling me I was looking in the wrong place. I’ve got it now: from itertools import product def my_product(inp): return (dict(zip(inp.keys(), values)) for values in product(*inp.values()) EDIT: after years more Python experience, I think a better solution is to accept kwargs rather than a dictionary of inputs; the call style is … Read more

Generate all permutations of a list without adjacent equal elements

This is along the lines of Thijser’s currently incomplete pseudocode. The idea is to take the most frequent of the remaining item types unless it was just taken. (See also Coady’s implementation of this algorithm.) import collections import heapq class Sentinel: pass def david_eisenstat(lst): counts = collections.Counter(lst) heap = [(-count, key) for key, count in … Read more

Generating permutations lazily

Yes, there is a “next permutation” algorithm, and it’s quite simple too. The C++ standard template library (STL) even has a function called next_permutation. The algorithm actually finds the next permutation — the lexicographically next one. The idea is this: suppose you are given a sequence, say “32541”. What is the next permutation? If you … Read more

Generate list of all possible permutations of a string

There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)