Hey guys,
My brain is broken today… this isn’t coldbox related, just a pure coldfusion thing.
how would I code to convert a collection of distinct arrays into an array of the “available combinations” of the distinct arrays…
Given I’m terrible at explaining things - an example perhaps.
arrayOne = [“opt1_yes”,“opt1_no”];
arrayTwo = [“opt2_yes”,“opt2_no”];
code to produce this expectedArray = [
[arrayOne[1],arrayTwo[1]],
[arrayOne[1],arrayTwo[2]],
[arrayOne[2],arrayTwo[2]],
[arrayOne[2],arrayTwo[1]]
];
which would also handle a varying amount of arrays and array values…
I’m sure I need to recurse… but it’s Thursday afternoon dead brain time methinks
any help appreciated. pseudo code 100% acceptable
Cheers
Steve
Aaron1
June 21, 2012, 4:01pm
2
If I understand you correctly, this should help:
// Our result array
result = [];
// Simply merge all the arrays into one to simplify the next block of code
tempArray = [];
tempArray.addAll( arrayOne );
tempArray.addAll( arrayTwo );
// Now, produce our result ensuring that only one entry exists for each unique item
// This will prevent duplicates
for(item in tempArray)
if (!arrayContains(result,item) arrayAppend(result,item);
Thanks Aaron… I’ll give the merge idea a run
the end result (in english) should be every combination available between the two(or more) original arrays.
if the values are
[x,y]
[a,b]
then the desired result is
[x,a]
[x,b]
[y,a]
[y,b]
Maybe I’m overthinking it…
Neil
June 21, 2012, 10:22pm
4
Is it not just:
arrayOne = [“opt1_yes”,“opt1_no”];
arrayTwo = [“opt2_yes”,“opt2_no”];
expectedArray = [];
for(itemA in arrayOne){
for(itemB in arrayTwo){
arrayAppend(expectedArray, [itemA, itemB]);
}
}
That works beautifully! and sooo elegant. thanks Nukes, owe you a (albeit virtual) beer
It needs to support any number of arrays with any number of array values, so I’ll need to massage it some.
thanks!
Neil
June 21, 2012, 10:55pm
6
I just noticed it was for a dynamic number of arrays, that’s where it gets hard…
Yep.
At the moment I’m heading down the path of converting the values to an array of structs which contains the value coordinates:
[
{“value”=“opt1_yes”,“arrayPosition”=1,“valuePosition”=1},
{“value”=“opt1_no”,“arrayPosition”=1,“valuePosition”=2},
{“value”=“opt2_yes”,“arrayPosition”=2,“valuePosition”=1},
{“value”=“opt2_yes”,“arrayPosition”=2,“valuePosition”=2},
]
Not sure I’m helping the situation, but I think I’m heading in the right direction
thoughts?
at least using this I can skip values that exist in the same arrayPosition, as they should never be in a result array together…