ios - Building combinations using recursion rather than using iteration -
ios - Building combinations using recursion rather than using iteration -
i trying customise combination method found in solution given here: combinations of different nsarray objects utilises recursion, instead of solution given, using iteration. reason why trying customise function increment performance of function starts slowing downwards when arrays start getting larger , there many combinations compute.
any advice on how done?
i think you'd have combine iteration , recursion. if want varying number of arrays came this...
first pass @ iterative method.
- (nsarray *)combinearrays:(nsarray *)arrays { // arrays array of arrays of elements want combine. nsmutablearray *combinations = [nsmutablearray array]; for(nsarray *array in arrays) { nsmutablearray *temp = [nsmutablearray array]; (id element in array) { if (combinations.count == 0) { // first level of array elements first array [temp addobject:@[element]]; } else { // re-create each array in combinations each new element , add together new element end (nsarray *array in combinations) { [temp addobject:[array arraybyaddingobject:element]; } } } // save current combinations combinations = temp; } homecoming combinations; }
i'm middle part can recursed single method. working on now.
- (nsarray *)combinearray:(nsarray *)combinations witharrays:(nsmutablearray *)arrays { // if there no arrays combine @ end of recursion homecoming combinations. if (!array || array.count == 0) { homecoming combinations; } // start "combine" first array empty array if (!combinations) { combinations = @[@[]]; } nsmutablearray *newcombinations = [nsmutablearray array]; nsarray *array = [arrays firstobject]; (id element in array) { (nsarray combination in combinations) { [newcombinations addobject:[combination arraybyaddingobject:element]; } } [arrays removeobjectatindex:0]; homecoming [self combinearray:newcombinations witharrays:arrays]; }
something might work. it's no faster iteration though.
take @ reply javascript - generating combinations n arrays m elements want in javascript. still have touch each element of each array 1 time though.
ios objective-c recursion nsarray
Comments
Post a Comment