Pascal triangle in Xcode console

Pascal triangle is one of the most famous recursive problems. It has a simple and elegant implementation in Objective-C as well as in many other languages. It turned out, that formatting the output seems more challenging than actual calculation for triangle elements:

+(NSInteger)pascalTriangleForRow: (NSInteger)row Column: (NSInteger)column
{
     if (row == column || column == 0) {
     return 1;
     } else {
     return [self pascalTriangleForRow:row-1 Column:column-1] + [self pascalTriangleForRow:row-1 Column:column];
     }
}
+(void)showTriangle
{
     NSMutableArray *triangle = [NSMutableArray new]; 
     for (NSInteger row = 0; row < 10; row ++) { 
         NSMutableArray *currentRow = [NSMutableArray new]; 
         for (NSInteger column = 0; column <= row; column++) { 
             [currentRow addObject:@([self pascalTriangleForRow:row Column:column])]; 
         } 
         NSString *rowAsString = [currentRow componentsJoinedByString:@" "];
         [triangle addObject:rowAsString]; 
      } 
      NSString *triangleString = [triangle componentsJoinedByString:@"\n"]; 
      NSLog(@"\n%@", triangleString);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s