[AHK v2] Generating Cartesian product recursively from array of sets

Post your working scripts, libraries and tools.
oif2003
Posts: 214
Joined: 17 Oct 2018, 11:43
Contact:

[AHK v2] Generating Cartesian product recursively from array of sets

03 Nov 2018, 23:43

Hello,

Here is a function that can give you an array of Cartesian product given an array of sets
For example:
Given s := [ ["one", "two"], [1, 2, 3] ]

g(s) returns:
[1] [one,1]
[2] [two,1]
[3] [one,2]
[4] [two,2]
[5] [one,3]
[6] [two,3]

This is usually done by nesting loops, but this function uses recursion instead so it can perform the same task on
arrays of arbitrary dimensions and lengths, such as:
[ [1, 2, 3, 4] , ["cat", "dog", "fish"] , ["desk", "chair"] , ["one", "two", "three", "four", "five"] ]

It also works on nested objects:
[ [[1,2], [3,4]], [[5,6], [7,8]], [[9,10], [11,12]] ]

This is useful when you have to iterate through each "coordinate" with nested loops. Instead of writing something like:

;Let "a" be an n by m array
for i, v in a
{
for j in v
{
f(a[i][j]) ;do stuff with a[i][j]
}
}

You can iterate over the returned array of "coordinates" from g(a). In this case we will get an array containing:
a[1][1]
a[2][1]
...
a[n][1]
a[n][2]
...
a[n][m]
It's particularily useful if you do not know the dimension of "a" ahead of time.

https://github.com/oif2003/AHK_v2_64bit ... ursion.ahk

Return to “Scripts and Functions (v2)”

Who is online

Users browsing this forum: No registered users and 31 guests