python,optimization,combinations,combinatorics,itertools

Yes: itertools.combinations print list(itertools.combinations(w, 2)) You mention this in your question - I'm not sure why you wouldn't look in the docs before asking on StackOverflow....

Like @TroyHaskin said, ndgrid is the way to go. On top of that you just need to do some pre and post processing. x = {{1,2}, {3}, {2,5}}; a = cellfun(@cell2mat, x, 'UniformOutput', 0); b = cell(size(a)); [b{:}] = ndgrid(a{:}); c = cellfun(@squeeze, b, 'UniformOutput', 0); d = cell2mat(cellfun(@(x) reshape(x,...

Let's assume that we have a set of integers { N1, N2, N3 }. What is the minimum sum that can be achieved by original numbers? It is the sum of elements in { N1-0.5, N2-0.5, N3-0.5 } array, we can rewrite it as: sum({ N1, N2, N3}) - 0.5...

python,combinations,combinatorics,puzzle,traveling-salesman

Problem is called maximum matching in bipartite graph or assignment problem. It is done by Hungarian algorithm. On Wikipedia page are implementations in different languages. There is python library munkres with an implementation....

algorithm,graph,combinations,combinatorics

You don't have to explicitly build the tree - you could use a recursive depth first search to achieve the same effect. At each point in the recursive depth first search you will have built a set of intervals covering [0,x] and you will want to extend this. To do...

c#,.net,linq,recursion,combinatorics

The best way to understand this code is to read the amazing serial post from Eric Lippert: Producing combinations, part one Producing combinations, part two Producing combinations, part three Producing combinations, part four Producing combinations, part five Basically, if we have a IEnumerable of 5 items, and want to get...

matlab,syntax,probability,combinatorics

brute force solution: [d1,d2,d3,d4]=ndgrid(0:4,0:4,0:4,0:4); d = d1+d2+d3+d4; i = find(d==4); [d1(i),d2(i),d3(i),d4(i)] ...

r,algorithm,function,permutation,combinatorics

Lets first choose a representative for each equivalence class. Lets say that vector p = {x_1 ... x_k} is a representative if it is lexicographical minimum from all p_i such that p_i ~ p. Notice that x_i is in range (1..x_j + 1) forall j < i. If that doesn't...

python,combinations,permutation,combinatorics

itertools.product should indeed be able to help you. The idea is this:- Consider A1, A2, ..., AN separated by slabs. There will be N-1 slabs. If there is a slab there is a segmentation. If there is no slab, there is a join. Thus, for a given sequence of length...

algorithm,recursion,combinatorics

Lets call the derangement function f for clarity. At f(n), there are n hats and n people. Everyone can choose from n-1 hats. Person 1 takes hat i from n-1 choices. Person i still has n-1 hats to choose from and everyone else has n-2 has to choose from (they...

I figured it out... you can identify all the single bit patterns like as follows, since the least significant 1 bit of any integer k is cleared when calculating k & (k-1): def onebits(x): while x > 0: # find least significant 1 bit xprev = x x &= x-1...

algorithm,set,subset,combinatorics

Let's compress your set of values to a representation like S = [1:2, 2:1, 3:2] where you just save the value and the count for every element and assign them some order. Let n be the size of the sequence S. You then have 2^count possibilities to select a subset...

(It is not specified in the question whether the groups are mutually exclusive or not; So, assume: 1. the groups are mutually exclusive 2. the subsets of groups (n1, n2, ...) will use the same elements in being filled) 3 just for the sake of argument |G1|=|G2|=|G3|=5 (The user can...

c#,logic,combinatorics,multiset

Edit: Sorry, had to run last evening. For arbitrary dimensionality you probably would have to use recursion. There's probably a way to do without it, but with recursion is most straightforward. The below is untested but should be about right. IEnumerable<int[]> getRows(int[][] possibleColumnValues, int[] rowPrefix) { if(possibleColumnValues.Any()) { //can't return...

scala,recursion,combinations,permutation,combinatorics

Let's call this operation "to riffle". Here is a clean idomatic solution: def allRiffles[T](stack1: List[T], stack2: List[T]): List[List[T]] = (stack1, stack2) match { case (x :: xs, y :: ys) => { allRiffles(xs, stack2).map(x :: _) ++ allRiffles(stack1, ys).map(y :: _) } case _ => List(stack1 ++ stack2) // at...

It is spelled like it sounds. f xs = [x-x' | x <- xs, x' <- xs] This of course will have each pair counted twice, once in order and once in reverse order, so half of the distances will be negative. Depending on what exactly you need, you may...

c#,tuples,permutation,combinatorics

Using Tuple, manually I'm afraid. So: var tuple = new Tuple<string, string, string>("a", "b", "c"); var combination_1 = String.Concat(tuple.Item1, tuple.Item2, tuple.Item3); var combination_2 = String.Concat(tuple.Item1, tuple.Item3, tuple.Item2); var combination_3 = String.Concat(tuple.Item2, tuple.Item1, tuple.Item3); var combination_4 = String.Concat(tuple.Item2, tuple.Item3, tuple.Item1); var combination_5 = String.Concat(tuple.Item3, tuple.Item1, tuple.Item2); var combination_6 = String.Concat(tuple.Item3, tuple.Item2,...

matlab,permutation,combinatorics

The following solution finds all the places in B where zeroes can go (T0), and where ones can go (T1). Then it loops through all those permutations, producing each mapping. A = [0 0 0 1 1 0 1 0]; B = [1 1 0 0 0 0 0 1];...

Providing that all the values in the list are unique: List <String> list = new List<String> { "a", "b", "c" }; var result = Enumerable .Range(1, (1 << list.Count) - 1) .Select(index => list.Where((item, idx) => ((1 << idx) & index) != 0).ToList()); To print out: Console.WriteLine(String .Join(Environment.NewLine, result .Select(line...

algorithm,complexity-theory,combinatorics,computation-theory

This is NP-Complete problem, and is a generalization of Hitting Set Problem. Proof of NP-Completeness follows. The problem is in NP (trivial - given a solution T, it is easy to check the intersection with each of Gi, and verify if its size is Ci). It is also NP-Complete, assuming...

sql-server,algorithm,tsql,combinatorics,knapsack-problem

Here is a possible solution. I will see if I can finish it tomorrow as it's almost 3 AM here now. The main logic is there. All that's left to be done is to trace back using the prev_w values. Just jump back (starting from the best_price row) till you...

Here is an efficient solution: Let's assume that we have picked a fixed element from the first list and we want to match it to the elements from the second and the third list with the same value. It uniquely determines the rotation of the second and the third list(we...

haskell,permutation,combinatorics

bhelkir's comment to the question has diagnosed your error correctly, so I'll skip that. The logic of your allCodes function is fundamentally sound (setting aside the permutations vs. combinations issue). One thing that's worth pointing out is that the same effect can be achieved as a one-liner by using two...

Here is a way to look at this using generating functions. The generating function (polynomial) for the number of ways to color a column with an even number of colored squares is a(x) = 1 + (R choose 2)x^2 + (R choose 4)x^4 + ... You are trying to compute...

C++ demands that a reference parameter to an unnamed temporary (like string()) must either be a const reference or an r-value reference. Either of those reference types will protect you from modifying a variable that you don't realize is going to be destroyed within the current expression. Depending on your...

java,algorithm,combinations,combinatorics

1.) k-permutation of n without repetion: http://www.statlect.com/comdis1.htm 2.) It depends on which you are searching for. For example, I offer you genetic algorithms which can find the best candidate based on a special heuristic if you can order a "goodness degree" to the possible solutions....

excel,vba,excel-vba,combinatorics

If I understand it right, then I would call your "sets" dimensions and your combinations possible addresses in those dimensions. For example in two dimensions x and y where x is in length 2 and y is in length 3 there are 6 possible points(x,y) if x and y elements...

Intro This is a numeric variation of the string algorithm we implemented in the other answer. It is faster and does not require either creating or sorting the pool. Algorithm Outline We can use integer numbers to represent your binary strings, which greatly simplifies the problem of pool generation and...

from itertools import product options = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']] for combo in product(*options): print("".join(combo)) gives Sometimes I love pizza Sometimes I love coke Sometimes I hate pizza Sometimes I hate coke ...

algorithm,computer-science,combinatorics,set-theory

We already know the answer for these cases (as you wrote in your examples): n=2 n=3 n=4 For n=5: You can partition from 2: 1 2 - 3 4 5. This is like dividing the 5 member set into two sets, first one n=2, and second one n=3. We can...

Using Jason McCreary's answer as inspiration, I found a solution that uses minimal memory. The largest the array $X can get is Π(|permutation list|), so for the example below 3×1×2 = 6. $input = 'pat'; $S = array( 'p' => array('b', 'f', 'v'), 'a' => array('e'), 't' => array('d', '')...

algorithm,combinatorics,probability-theory

I have completely reviewed my response : **Bugs fixed** in : `array function computeRepettition(array $a);` **Avoid** increment of repetition if triad was already found in pass-1 **Return** an array of arrays, and the number of repetition of each triad is set in '**numberOfRepetition**', the triad in self is the key...

java,string,arraylist,combinatorics

Since you have a fixed number of lists, the simplest way is to just use nested loops: List<Sentence> sentences = new ArrayList<>(); for(String verb_hypernym : wordnet.getHypernyms(verb, POS.VERB)) for(String object_hypernym : wordnet.getHypernyms(object, POS.NOUN)) for(String subject_hypernym : wordnet.getHypernyms(subject, POS.NOUN)) sentences.add(new Sentence(verb_hypernym, object_hypernym, subject_hypernym)); return sentences; Or, to avoid calling getHypernyms more often...

mapping,combinatorics,computation-theory,np-complete,set-theory

You could create a bipartite graph in the following manner: For each element in the set X create a node in the U disjoint set of the graph For each subset in the set S create a node in the V disjoint set of the graph If element of X...

arrays,algorithm,combinatorics

As burnpanck has explained in his answer, to make sure that when you pick any k elements in the array, and at least one of them is in range [L,R], we need to make sure that there are at least n - k + 1 numbers in range [L,R] in...

math,permutation,combinatorics

http://en.wikipedia.org/wiki/Permutation The notion of permutation relates to the act of rearranging, or permuting, all the members of a set into some sequence or order (unlike combinations, which are selections of some members of the set where order is disregarded). For example, written as tuples, there are six permutations of the...

c++,templates,c++11,variadic-templates,combinatorics

This is based on the PowerPack solution, but the filtering of too-long entries happens in each step and is therefore more efficient than just filtering at the end. Step 1: NAppend<N,Pack<...>,T> only appends the new type T to the Pack<...> if it does not have more than N entries afterwards....

python,computer-science,permutation,combinatorics

Using itertools.combinations: >>> import itertools >>> list(itertools.combinations(['foo', 'bar', 'la'], 2)) [('foo', 'bar'), ('foo', 'la'), ('bar', 'la')] ...

matlab,permutation,combinatorics

To assure no indices coincide before and after the shuffle, you can use a rejection method, i.e. keep trying until success: N = 10000; original_indices = 1:N; done = 0; while ~done shuffled_indices = randperm(N); %// this will hold the result when loop is exited done = all(shuffled_indices~=original_indices); end According...

This is what I would do, with, e.g., s=1:2: 1) Represent subsets with a 0/1 matrix for each element's membership. subsets = as.matrix(do.call(expand.grid,replicate(length(s),0:1,simplify=FALSE))) which gives Var1 Var2 [1,] 0 0 [2,] 1 0 [3,] 0 1 [4,] 1 1 Here, the first row is the empty subset; the second, {1};...

After giving my problem some more thoughts I came up with a solution I am quite proud of. This solution: will find all possible complete variants, that is, variants where no additional item can be added without causing a conflict will also find a few non-complete variants. I can live...

string,algorithm,probability,combinatorics,discrete-mathematics

Suppose you build up palindrome-free strings one letter at a time. For the first letter, you have M choices, and for the second, you have M-1, since you can't use the first letter. This much is obvious. For every letter after the first two, you can't use the previous letter,...

Not sure about you list structure, if you do need to take slices you can use itertools.islice and store all lists in a dict: from itertools import islice l = iter([0.0, 1.0, 0.1, #mass 1.0, 5.0, 1.0,#velocity 45.0 ,47.0, 1.0, #angle in degrees 0.05, 0.07, 0.1, #drag coeff. 0.0, 0.0...

For the 'full square, excluded diagonal' as you've asked for its string[] teams = {"Boston","San Francisco","Red Sox","Giants"}; for (string home:teams) { for (string away:teams) { if (home==away) continue; System.out.println(home + " x " + away); } } You can alternatively use a for loop with i, j etc. You would...

python,list,combinatorics,itertools

You can do this with itertools.product and zip from itertools import product print [zip(A, item) for item in product(B, repeat=len(A))] Output [[('a', 1), ('b', 1), ('c', 1)], [('a', 1), ('b', 1), ('c', 2)], [('a', 1), ('b', 2), ('c', 1)], [('a', 1), ('b', 2), ('c', 2)], [('a', 2), ('b', 1), ('c',...

You just forget to output the first result with s from 0 to r - 1. ... permuted_items.append([items[k] for k in s]) for i in xrange(1, C(n,r)): ... # rest ...

Here's my attempt at a recursive solution (see comments in Java code): private static int result = 0; private static int n = 3; public static void g(int right,int spur){ if (right == n) // all trains are on the right track result++; else if (right + spur < n)...

python,performance,generator,combinatorics

Here are some generators based on algorithms attributed to Knuth. subsets4 generates all subsets of 1..n having k or less elements subsets5 restricts the subsets generated by subsets4 to those having a max difference of w subsets generates all subsets of 1..n of length exactly k subsets2 restricts the subsets...

python,algorithm,permutation,combinatorics

Doable with a backtracking search. Python 3: import itertools import operator def valid(cols_so_far): for i, col1 in enumerate(cols_so_far): for col2 in cols_so_far[i + 1:]: if any(map(operator.eq, col1, col2)): return False return True def enum(letters, k, cols_so_far=None): if cols_so_far is None: cols_so_far = (tuple(letters),) if not valid(cols_so_far): pass elif len(cols_so_far) ==...

algorithm,erlang,dynamic-programming,combinatorics,lis

Your current implementation of lis/1 function is O(n), I don't see any reasons to doubt. But there is some problem. You implementation doesn't actually calculate valid LIS. Try lis(lists:reverse([1,2,3,4,1,2])) for error example. Longest increasing sequense is [1,2,3,4], right? But your algorith returns 6 as result. First error in your algorithm...

java,arrays,permutation,combinatorics

static <T> void swap(T[] a, int i, int j) { T t = a[i]; a[i] = a[j]; a[j] = t; } static void permutation(int[][] perm, int n, List<int[][]> result) { int size = perm.length; if (n >= size) result.add(Arrays.copyOf(perm, size)); else for (int i = n; i < size; i++...

matlab,matrix,combinatorics,diophantine

Math: Instead of going the hypercube-way, we solve the equation x(1) + x(2) + ... + x(n) = 1 where each x(i) can vary in [0, 1/k, 2/k, ... (k-1)/k, 1] instead. In your case k will be 10, as this will then result in the percentages [0, 10, 20,...

Their solution uses recursion to express all possible combinations of the numbers in a pretty clever way. But clever does not always mean readable or easy to understand (which all code should be) so don't feel bad for not getting it right away. Personally, I would not consider this good...

algorithm,set,permutation,combinatorics,sequences

What you are looking for is the number of surjective functions whose domain is a set of K elements (the K positions that we are filling out in the output sequence) and the image is a set of S elements (your input set). I think this should work: static int...

performance,matlab,matrix,combinations,combinatorics

To replace nchoosek(1:N,2) With bsxfun - [Y,X] = find(bsxfun(@gt,[1:N]',[1:N])) pair = [X, Y]; With tril and find only (without ind2sub) - [y,x] = find(tril(true(N),-1)) pair = [X, Y]; ...

A normal permutation generation algorithm should work, all you need to do is tweak it to print prefixes of the permutation. I recently gave an answer for permutations, but it is in python. Should be easy to convert to Java. This is the code, with the tweak of prefix printing...

algorithm,sorting,combinations,combinatorics,gray-code

While I really appreciate the efforts from @tucuxi and @David Eisenstadt, I found some issues with the Hamiltonian approach, namely that it didn't solve for certain values of n and k and certain elements were also unnecessarily discriminated. I decided to give the ideas listed in my question a go...

python,numpy,scikit-learn,combinatorics

Since you have the numpy tag, the following works: >>> N = 5 >>> idx = np.arange(N) >>> idx = idx[1:] - (idx[:, None] >= idx[1:]) >>> idx array([[1, 2, 3, 4], [0, 2, 3, 4], [0, 1, 3, 4], [0, 1, 2, 4], [0, 1, 2, 3]]) And you...

matlab,matrix,combinations,combinatorics,cartesian-product

You were on the right track with allcomb. You are in fact looking for the cartesian product: [e0, e1, e2] x [e0, e1, e2] x [e0, e1, e2] == [e0, e1, e2]^3. You don't need allcomb though, as ndgrid can already do this. Let's start with your code. It has...

java,combinations,combinatorics

This can be easily done without recursion. The idea is to have array of size k (length of subsequence), which at every moment keeps sequence of indices of elements in the input array. On every iteration, try to generate new index sequence if this is possible. First index sequence will...

c++,algorithm,math,combinatorics

Actually, your formula is incorrect. The correct one can be found here: https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_necklaces My implementation of it has just passed all the tests....

Your guess was correct; recursion is your friend for this challenge. Here is a simple solution: public static IEnumerable<string> Combinations(string input) { int firstZero = input.IndexOf('0'); // Get index of first '0' if (firstZero == -1) // Base case: no further combinations return new string[] { input }; string prefix...

algorithm,set,combinatorics,backtracking

You can try the recursive answer if your set is not to big (or else use stack) : The principle is the following, you have a function that give back : rec_func(SET) = List of List of Set And work as follow : rec_func(SET) = if SET = {empty}: //...

python,combinatorics,cartesian-product

It is impossible to filter and there is a closed form formula (see the mathematics here). Here is how to solve this problem in python (inspired from here): Install sympy in order to have symbolic algebra in python (download, decompress, go to the folder, python setup.py install, and that's it)...

python,combinatorics,string-comparison,string-matching

If I understand you correctly you first need to construct all circular permutations of the input sequence and then determine the (lexicographically) smallest element. That is the root of your symbol loop. Try this: def normalized(s): L = [s[i:] + s[:i] for i in range(len(s))] return sorted(L)[0] This code works...

algorithm,dynamic-programming,combinatorics,subsequence

If the sum of all your elements is not too big (within millions), then you can do a solution similar to a knapsack problem. Your DP state is a difference between two sets, and for every element you iterate over all the differences you know so far, and update them....