Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chrisswong/2c8e982da258aa0fc963 to your computer and use it in GitHub Desktop.
Save chrisswong/2c8e982da258aa0fc963 to your computer and use it in GitHub Desktop.
NSArray * bruteForceProduct(NSArray *array) {
NSMutableArray *outputArray = [NSMutableArray arrayWithCapacity:[array count]];
for (NSInteger i = 0 ; i < [array count]; i++) {
NSInteger currentNumber = 1;
for (NSInteger j = 0 ; j < [array count] ; j++) {
if ( i != j ) {
currentNumber *= [array[j] integerValue];
}
}
[outputArray addObject:@(currentNumber)];
}
return [NSArray arrayWithArray:outputArray];
}
NSArray * cleverProduct(NSArray *array) {
NSMutableArray *productArray = [NSMutableArray arrayWithCapacity:[array count]];
for (NSInteger i = 0; i < [array count]; i++) {
[productArray addObject:@1];
}
NSInteger product = 1;
for (NSInteger i = 0; i < [productArray count]; i++) {
productArray[i] = @(product);
product *= [array[i] integerValue];
}
product = 1;
for (NSInteger i = [productArray count] - 1; i >= 0; i--) {
productArray[i] = @([productArray[i] integerValue] * product);
product *= [array[i] integerValue];
}
return [NSArray arrayWithArray:productArray];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment