As a follow up to my question here, I am trying to implement the following PHP function in Objective-C, which will generate a cartesian product:
function array_cartesian_product($arrays)
{
$result = array();
$arrays = array_values($arrays);
$sizeIn = sizeof($arrays);
$size = $sizeIn > 0 ? 1 : 0;
foreach ($arrays as $array)
$size = $size * sizeof($array);
for ($i = 0; $i < $size; $i ++)
{
$result[$i] = array();
for ($j = 0; $j < $sizeIn; $j ++)
array_push($result[$i], current($arrays[$j]));
for ($j = ($sizeIn -1); $j >= 0; $j --)
{
if (next($arrays[$j]))
break;
elseif (isset ($arrays[$j]))
reset($arrays[$j]);
}
}
return $result;
}
Here is what I have so far:
-(NSArray *) array_cartesian_product:(NSArray *)arrays {
NSMutableArray *result = [[NSMutableArray alloc] init];
int sizeIn = [arrays count];
int size = (sizeIn > 0) ? 1 : 0;
for(id array in arrays)
size *= [array count];
for(int i = 0; i < size; i++) {
for (int j = 0; j < sizeIn; j++) {
[result insertObject:[arrays objectAtIndex:j] atIndex:i];
}
for (int j = (sizeIn - 1); j >= 0; j--) {
// ?????
}
}
return result;
}
I'm getting lost when trying to code the equivalent of PHP's next
, current
and reset
functions, as I dont know how to reference the internal pointer to the array.
How can I implement the last block of code and get an equivalent function?
In mathematics, the Cartesian Product of sets A and B is defined as the set of all ordered pairs (x, y) such that x belongs to A and y belongs to B. For example, if A = {1, 2} and B = {3, 4, 5}, then the Cartesian Product of A and B is {(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)}.
Let A and B be two sets, Cartesian productA × B is the set of all ordered pair of elements from A and B. A × B = {{x, y} : x ∈ A, y ∈ B} Let A = {a, b, c} and B = {d, e, f} The Cartesian product of two sets is. A x B = {a, d}, {a, e}, {a, f}, {b, d}, {b, e}, {b, f}, {c, d}, {c, e}, {c, f}}
NSArray *cartesianProductOfArrays(NSArray *arrays)
{
int arraysCount = arrays.count;
unsigned long resultSize = 1;
for (NSArray *array in arrays)
resultSize *= array.count;
NSMutableArray *product = [NSMutableArray arrayWithCapacity:resultSize];
for (unsigned long i = 0; i < resultSize; ++i) {
NSMutableArray *cross = [NSMutableArray arrayWithCapacity:arraysCount];
[product addObject:cross];
unsigned long n = i;
for (NSArray *array in arrays) {
[cross addObject:[array objectAtIndex:n % array.count]];
n /= array.count;
}
}
return product;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With