I am not sure but I think you want something like this: let pairs = function | [] -> [] | (x::xs) -> List.map (fun x' -> (x,x')) xs let rec hSquare xs = match xs with | [] -> [] | (_::ys) -> pairs xs @ hSquare ys with...

python,list,python-3.x,itertools,cartesian-product

Build a generator function which can yield as many values as you want and use it in the product, like this >>> from itertools import product >>> def get_chunks(items, number=3): ... for i in range(len(items) - number + 1): ... yield items[i: i + number] ... ... and then define...

This works: with open('list1.txt', 'r') as l1, open('list2.txt', 'r') as l2, open('list3.txt', 'w') as l3: for left_part in l1: for right_part in l2: l3.write('%s%s\n' % (left_part.replace("\n",""), right_part.replace("\n",""))) l2.seek(0) ...

Ok I came up with a solution. It might not be the best one and there are for sure some improvements of the code possible but its enough for my purposes and in case someone needs it too: vector<string> getProducts(vector<string> s) { int combinations = 1; vector<string> res; for (unsigned...

python,arrays,numpy,vectorization,cartesian-product

Two more approaches could be suggested here. Using matrix-multiplication with np.dot: np.dot(x[:,None],y[None]).ravel() With np.einsum: np.einsum('i,j->ij',x,y).ravel() Runtime tests In [31]: N = 10000 ...: x = np.random.rand(N) ...: y = np.random.rand(N) ...: In [32]: %timeit np.dot(x[:,None],y[None]).ravel() 1 loops, best of 3: 302 ms per loop In [33]: %timeit np.einsum('i,j->ij',x,y).ravel() 1 loops,...

php,algorithm,cartesian-product

I solved my issue with memory by performing a depth first cartesian product. I can weigh the solutions one at a time and retain some if I choose or simply output them as I am doing here in this code snippet. The main inspiration for this solution came from the...

You could create an extension method like the following: public static class EnumerableExtensions { public static IEnumerable<TValue []> Permutations<TKey, TValue>(this IEnumerable<TKey> keys, Func<TKey, IEnumerable<TValue>> selector) { var keyArray = keys.ToArray(); if (keyArray.Length < 1) yield break; TValue [] values = new TValue[keyArray.Length]; foreach (var array in Permutations(keyArray, 0, selector, values))...

c,arrays,preprocessor,c-preprocessor,cartesian-product

Using Chaos and a compiler with a good preprocessor (e.g. GCC): #include <stdio.h> #include <stdlib.h> #include <chaos/preprocessor/algorithm/for_each_product.h> #include <chaos/preprocessor/recursion/expr.h> #include <chaos/preprocessor/seq/core.h> #include <chaos/preprocessor/seq/elem.h> #include <chaos/preprocessor/seq/enumerate.h> #define A(l, h) \ const unsigned char \ a1[] = { CHAOS_PP_SEQ_ENUMERATE(l) }, \ a2[] = { CHAOS_PP_SEQ_ENUMERATE(h) }, \ a21[] = { \ CHAOS_PP_SEQ_ENUMERATE(...

If you need an unknown-at-compile-time set of nested index loops, you can use code like this. package main import "fmt" // NextIndex sets ix to the lexicographically next value, // such that for each i>0, 0 <= ix[i] < lens(i). func NextIndex(ix []int, lens func(i int) int) { for j...

c#,arrays,list,nested,cartesian-product

You need parentheses around the query (from itemset1 in itemarr1 from itemset2 in itemarr2 from itemset3 in itemarr3 select new[] { itemset1, itemset2, itemset3 }).ToList(); ...

makefile,gnu-make,cartesian-product

Why not just do it in two loops? obj := $(foreach X,$(prefix),$(foreach Y,$(base),$X$Y)) ...

python,permutation,product,itertools,cartesian-product

Simple: itertools.product(pos_1, pos_2, pos_3) This can be iterated over; if you want a list, just pass it to list. What exactly is the issue? Edit: This produces tuples of the items from each source. If you want to join them back into strings, you can do that manually when you...

c#,list,combinations,cartesian-product,cartesian

As long as you only want to create the cartesian product of two sets you can use LINQ SelectMany: var n = 2; var numbers = Enumerable.Range(0, n + 1); var cartesianProduct = numbers.SelectMany(_ => numbers, (a, b) => Tuple.Create(a, b)); When cartesianProduct is enumerated it will generate 9 tuples...

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)...

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...

Use a cell-array GRID on the receiving end, to get a programmatic comma-separated list: N = numel(sets); [GRID{1:N}] = ndgrid(sets{:}); mat_ref = reshape(cat(N+1,GRID{:}),[],N) (No need to declare GRID = cell(..) first.)...

matlab,vector,combinations,cartesian-product

a = [1 2 3] a = 1 2 3 >> b = [4 5 6] b = 4 5 6 >> c=allcomb(a,b)' c = 1 1 1 2 2 2 3 3 3 4 5 6 4 5 6 4 5 6 You can find the allcomb function here...

r,join,data.table,cartesian-product

Question 1: Looks great! But the equivalent of inner join is to also add nomatch=0L. Otherwise you'd also get all the rows from dtMoveB. We can't make use of by=.EACHI here AFAICT. Read this answer and the answer linked under this comment for understanding the purpose of allow.cartesian = TRUE....

sql,sql-server,join,outer-join,cartesian-product

I can't fathom why you want to do this, but... You need to create an artificial join between table1 and table2, and then link that to the master table. One way of doing that is by ranking the rows in order. eg: SELECT p.pid, p.lname,p.fname, thingone, thingtwo FROM person p...

mysql,sql,sql-server,count,cartesian-product

Specifying multiple tables in the FROM clause is equivalent to doing a CROSS JOIN. You can use UNION ALL to solve that problem. WITH summary(year, posts, albums, pictures) AS ( SELECT year, posts, 0, 0 FROM PostsPerYear UNION ALL SELECT year, 0, albums, 0 FROM AlbumsPerYear UNION ALL SELECT year,...

mysql,sql,select,join,cartesian-product

A Cartesian join joins every record in the first table with every record in the second table, so since your table has 7 rows and it's joined with itself, it should return 49 records had you not had a where clause. Your where clause only allows records where a's balance...

c++,string,vector,temporary,cartesian-product

You may try the following approach #include <iostream> #include <vector> #include <string> int main() { std::vector<std::string> final{ "a", "b", "c" }; std::vector<std::string> temp{ "1", "2" }; auto n = final.size(); final.resize( final.size() * temp.size() ); for ( auto i = n, j = final.size(); i != 0; --i ) {...

python-2.7,cartesian-product,radix-tree

Here's a simple, first-pass attempt at such a function: def compress_list(alist): """Compress a list of colon-separated strings into a more compact representation. """ components = [ss.split(':') for ss in alist] # Check that every string in the supplied list has the same number of tags tag_counts = [len(cc) for cc...

python,dictionary,cartesian-product

You're close: from itertools import product, izip for i in product(*p.itervalues()): print dict(izip(p, i)) {'a': 1, 'b': 5} {'a': 1, 'b': 6} ... {'a': 3, 'b': 8} ...

join,relational-algebra,cartesian-product,functional-dependencies,lossless

It helps if we demystify the concept of lossless decomposition a bit: it really just means that joining R1, R2 and R3 should yield the original R. Do you know the chase test a.k.a "the tableau method"? It's a cool algorithm to test for losslessness. It's easy to program, and...

dictionary,racket,cartesian-product

Here's a method that totally uses higher-order functions (foldr, append-map, and map; now also with compose1, curry, and curryr): (define (cartesian-product . lists) (foldr (lambda (a b) (append-map (compose1 (curryr map b) (curry cons)) a)) '(()) lists)) Pardon the terrible parameter names. One day I'll come up with something good....

Problems in your code: sizeof(first)(and sizeof(second)) gives number of string literals in the array * sizeof(char*). You need to discard the second part. Just divide it by sizeof(char*) or sizeof(*str) as @BLUEPIXY suggested which is the same as sizeof(str[0]): int size = (sizeof(first) / sizeof(*first)) * (sizeof(second) / sizeof(*second)); Your...

The simplest way is to use recursion: real matrix cart_prod(pointer vector c_list ,| real scalar curr_i){ if(curr_i==.) curr_i=1 myret = (*c_list[curr_i]) if (curr_i<length(c_list)){ ret = cart_prod(c_list, curr_i+1) myret = mm_expand(myret,rows(ret),1,1), mm_expand(ret, rows(myret),1,0) } return(myret) } cart_prod(c_list) This will work even if the vectors pointed to from c_list are of different...

python,permutation,itertools,dice,cartesian-product

As Calum noted, you should use the built-in itertools for these common loops. In your case, you would want: import itertools results = [sum(x) for x in itertools.product(range(1,5),repeat=9)] range(1,5) represents the 4 sides of the die repeat=9 represents the 9 dice you want to roll See itertools.product for doc...

I think I got it, I googled "PHP combinations" (Assuming that a combination is similar to a Cartesian product, I think it is :s) and used this code as a base. The change I needed to make was instead of merging the arrays I had to use a union because...