How can I implement this Objective-C implementation of the Cartesian product function?

As a continuation of 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 still have:

 -(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 get lost when trying to encode the equivalent of the PHP functions next , current and reset , since I do not know how to refer to an internal pointer to an array.

How can I implement the last block of code and get an equivalent function?

+6
source share
2 answers
 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; } 
+8
source

NSArray NSMutableArray does not have the following current reset functions. I think you can write a class to implement such a function

 @interface myArray { NSMutableArray* array;//the real array int index;//hole the index } -(id)current; -(id)next; -(id)reset; @end 

function 3 will change the index,

-2
source

Source: https://habr.com/ru/post/902361/


All Articles