Algorithm to list all unique permutations of numbers contain duplicates

The simplest approach is as follows: Sort the list: O(n lg n) The sorted list is the first permutation Repeatedly generate the “next” permutation from the previous one: O(n! * <complexity of finding next permutaion>) Step 3 can be accomplished by defining the next permutation as the one that would appear directly after the current … Read more

Given a list of elements in lexicographical order (i.e. [‘a’, ‘b’, ‘c’, ‘d’]), find the nth permutation – Average time to solve?

9 min, including test import math def nthperm(li, n): n -= 1 s = len(li) res = [] if math.factorial(s) <= n: return None for x in range(s-1,-1,-1): f = math.factorial(x) d = n / f n -= d * f res.append(li[d]) del(li[d]) return res #now that’s fast… nthperm(range(40), 123456789012345678901234567890)

Generating all combinations with repetition using MATLAB

We can use the bijection mentioned in the wikipedia article, which maps combinations without repetition of type n+k-1 choose k to k-multicombinations of size n. We generate the combinations without repetition and map them using bsxfun(@minus, nchoosek(1:n+k-1,k), 0:k-1);. This results in the following function: function combs = nmultichoosek(values, k) %// Return number of multisubsets or … Read more

Get all pairs in a list using LINQ

Slight reformulation of cgeers answer to get you the tuples you want instead of arrays: var combinations = from item1 in list from item2 in list where item1 < item2 select Tuple.Create(item1, item2); (Use ToList or ToArray if you want.) In non-query-expression form (reordered somewhat): var combinations = list.SelectMany(x => list, (x, y) => Tuple.Create(x, … Read more