-
-
Save tawrahim/3102106 to your computer and use it in GitHub Desktop.
Description of Program (CS193P Assignment 2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (NSString *) descriptionOfProgram:(id)program | |
{ | |
NSMutableArray *stack; | |
if ([program isKindOfClass:[NSArray class]]) stack = [program mutableCopy]; | |
NSString *programDescription = @""; | |
while (stack.count) { | |
programDescription = [programDescription stringByAppendingString:[self descriptionOfTopOfStack:stack]]; | |
if (stack.count) { | |
programDescription = [programDescription stringByAppendingString:@", "]; | |
} | |
} | |
return programDescription; | |
} | |
+ (NSString *) descriptionOfTopOfStack:(NSMutableArray *)stack | |
{ | |
NSString *description = @""; | |
id topOfStack = [stack lastObject]; | |
if (topOfStack) [stack removeLastObject]; | |
if ([topOfStack isKindOfClass:[NSNumber class]]){ | |
description = [NSString stringWithFormat:@"%g", [topOfStack doubleValue]]; | |
} else if ([topOfStack isKindOfClass:[NSString class]]) { | |
if ([self isOperation:topOfStack] && [self isSingleOperandOperation:topOfStack]) { | |
description = [NSString stringWithFormat:@"%@(%@)", topOfStack, [self descriptionOfTopOfStack:stack]]; | |
} else if ([self isOperation:topOfStack] && ![self isSingleOperandOperation:topOfStack] && ![self isNoOperand:topOfStack]) { | |
NSString *first = [self descriptionOfTopOfStack:stack]; | |
NSString *second = [self descriptionOfTopOfStack:stack]; | |
if ([topOfStack isEqualToString:@"+"] || [topOfStack isEqualToString:@"-"]){ | |
description = [NSString stringWithFormat:@"(%@%@%@)",second,topOfStack,first]; | |
} else description = [NSString stringWithFormat:@"%@%@%@",second,topOfStack,first]; | |
} else description = topOfStack; | |
} | |
return description; | |
} | |
+ (BOOL) isOperation:(NSString *) stringInQuestion | |
{ | |
NSSet *operationsSet = [NSSet setWithObjects: @"+", @"-", @"*", @"/", @"sin", @"cos", @"sqrt", @"π", @"+/-", @"e", @"log", nil]; | |
return [operationsSet containsObject:stringInQuestion]; | |
} | |
+ (BOOL) isSingleOperandOperation:(NSString *) operationInQuestion | |
{ | |
NSSet *operationSet = [NSSet setWithObjects:@"sin", @"cos", @"sqrt", @"log", nil]; | |
return [operationSet containsObject:operationInQuestion]; | |
} | |
+ (BOOL)isNoOperand:(NSString *)operation | |
{ | |
return [[NSSet setWithObjects:@"π",@"x",@"y",@"foo", nil] containsObject:operation]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment