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

Obtaining a powerset of a set in Java

Yes, it is O(2^n) indeed, since you need to generate, well, 2^n possible combinations. Here’s a working implementation, using generics and sets: public static <T> Set<Set<T>> powerSet(Set<T> originalSet) { Set<Set<T>> sets = new HashSet<Set<T>>(); if (originalSet.isEmpty()) { sets.add(new HashSet<T>()); return sets; } List<T> list = new ArrayList<T>(originalSet); T head = list.get(0); Set<T> rest = new … Read more

How to get all subsets of a set? (powerset)

The Python itertools page has exactly a powerset recipe for this: from itertools import chain, combinations def powerset(iterable): “powerset([1,2,3]) –> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)” s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) Output: >>> list(powerset(“abcd”)) [(), (‘a’,), (‘b’,), (‘c’,), (‘d’,), (‘a’, ‘b’), (‘a’, ‘c’), (‘a’, ‘d’), (‘b’, ‘c’), (‘b’, … Read more