如何完成笛卡尔积函数的Objective-C实现? [英] How can I complete this Objective-C implementation of a cartesian product function?
本文介绍了如何完成笛卡尔积函数的Objective-C实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为我的问题的后续跟踪这里,我试图在Objective-C中实现以下PHP函数,它将生成一个笛卡尔积:
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;
}
以下是我目前的情况:
-(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;
}
我在尝试编写相当于PHP的下一个
,当前
和重置
函数,因为我没有知道如何引用数组的内部指针。
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?
推荐答案
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;
}
这篇关于如何完成笛卡尔积函数的Objective-C实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文