6
\$\begingroup\$

How can I optimize the if condition in this snippet? The only one difference is && [self isCurrentPosition:i]. How can I make it a single if, including the condition val?

Note: self is a category of NSArray.

- (void) cleanTextfieldExcluding:(int)current checkPosition:(BOOL)val {
  for ( int i=0; i<[self count]; i++ ) {

    // -----------
    if ( val ) {  // this IF block is very bad
      if ( i != current && [self isCurrentPosition:i] )
        [self replaceObjectAtIndex:i withObject:@""];
    } else {
      if ( i != current ) 
        [self replaceObjectAtIndex:i withObject:@""];
    }
    // -----------

  }
}
\$\endgroup\$
  • \$\begingroup\$ you cannot merge it go a single if. \$\endgroup\$ – zdd Nov 28 '12 at 10:18
3
\$\begingroup\$

It seems that the code in if will be executed only if i != current and val && [self isCurrentPosition:i] or !val, so you could merge all the ifs into one:

- (void) cleanTextfieldExcluding:(int)current checkPosition:(BOOL)val {
  for ( int i=0; i<[self count]; i++ ) {

    // -----------
    if ( (i != current) && (!val || [self isCurrentPosition:i]) ) {
        [self replaceObjectAtIndex:i withObject:@""];
    }
    // -----------

  }
}
\$\endgroup\$
  • \$\begingroup\$ just saw the answer below me and OMG it was better than mines(performs one less logic operation) so i updated mines too. :P \$\endgroup\$ – resgh Nov 28 '12 at 15:32
  • \$\begingroup\$ -1. Your answers are now the same because you copied his code (and didn't upvote his answer). \$\endgroup\$ – seand Nov 28 '12 at 16:29
5
\$\begingroup\$

the (val · ¬cur · pos) | (¬val · ¬cur) = ¬cur (val·pos | ¬val) = ¬cur (pos | ¬val). So, the condition is

if ( (i != current) && (!val || [self isCurrentPosition:i]) ) {
        [self replaceObjectAtIndex:i withObject:@""];
    }

You just must practise factoring out the common subexpressions and subprograms and learn how to use the Carnot maps for boolean minimization.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.