Skip to content

Instantly share code, notes, and snippets.

@Elephruit
Created July 9, 2012 15:50
Show Gist options
  • Save Elephruit/3077271 to your computer and use it in GitHub Desktop.
Save Elephruit/3077271 to your computer and use it in GitHub Desktop.
Description of Program (CS193P Assignment 2)
+ (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];
}
@dugweb
Copy link

dugweb commented Jul 12, 2012

Thanks for posting these. Had trouble getting the ball rolling on this one, but these helped with understanding it all very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment