Generate all binary strings of length n with k bits set

This method will generate all integers with exactly N ‘1’ bits. From https://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation Compute the lexicographically next bit permutation Suppose we have a pattern of N bits set to 1 in an integer and we want the next permutation of N 1 bits in a lexicographical sense. For example, if N is 3 and the … Read more

How to generate all permutations of a string in PHP?

You can use a back tracking based approach to systematically generate all the permutations: // function to generate and print all N! permutations of $str. (N = strlen($str)). function permute($str,$i,$n) { if ($i == $n) print “$str\n”; else { for ($j = $i; $j < $n; $j++) { swap($str,$i,$j); permute($str, $i+1, $n); swap($str,$i,$j); // backtrack. … Read more

Finding all possible permutations of a given string in python

The itertools module has a useful method called permutations(). The documentation says: itertools.permutations(iterable[, r]) Return successive r length permutations of elements in the iterable. If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated. Permutations are emitted in lexicographic sort order. … Read more

Permutations in JavaScript?

Little late, but like to add a slightly more elegant version here. Can be any array… function permutator(inputArr) { var results = []; function permute(arr, memo) { var cur, memo = memo || []; for (var i = 0; i < arr.length; i++) { cur = arr.splice(i, 1); if (arr.length === 0) { results.push(memo.concat(cur)); } … Read more