Skip to content

Instantly share code, notes, and snippets.

@tawrahim
Forked from Elephruit/descriptionOfProgram.m
Created July 13, 2012 01:04
Show Gist options
  • Save tawrahim/3102106 to your computer and use it in GitHub Desktop.
Save tawrahim/3102106 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];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment