Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple math expression solve in objective c from left to right

I simply have this expression in objective c NSString: @"10+5*2". I wanted to solve this expression automatically and came across to a solution:

UIWebView *webView = [[UIWebView alloc] init];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
NSLog(@"%@",result); 

The above works well but it produces a result: 20. Actually this evaluates the "*" first means first it does 5*2 = 10 + 10. But I want to remove this precedence and simply wants each operator having same precedence with left to right so that answer could be 10+5 = 15 * 2 = 30.

Although writing own function is the last option but I really don't want to mess-up with the string functions. I would like to use something built in.

Thanks,

******* Working solution ********

Thanks for all your help Eiko and Ozair!! Based on their answers I have written this bunch of code which works perfectly for me!

NSString *expression = lblBox.text; // Loads the original expression from label.
    expression = [expression stringByReplacingOccurrencesOfString:@"+" withString:@")+"];
    expression = [expression stringByReplacingOccurrencesOfString:@"-" withString:@")-"];
    expression = [expression stringByReplacingOccurrencesOfString:@"*" withString:@")*"];
    expression = [expression stringByReplacingOccurrencesOfString:@"/" withString:@")/"];


    NSUInteger count = 0, length = [expression length];
    NSRange range = NSMakeRange(0, length); 

    while(range.location != NSNotFound)
    {
        range = [expression rangeOfString: @")" options:0 range:range];
                 if(range.location != NSNotFound)
                 {
                     range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
                     count++; 
                 }
    }

    for (int i=0; i<count; i++) {
        expression = [@"(" stringByAppendingString:expression];
    }


    UIWebView *webView = [[UIWebView alloc] init];
    NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
    [webView release];
    NSLog(@"%@ = %@",expression, result);
like image 467
necixy Avatar asked Dec 17 '22 12:12

necixy


1 Answers

Not sure if it's the same as @Ozair Kafray says...

For each operator that you append to the string, add a ) first and add the matching ( at the beginning. I.e.

10
(10 ) +
(10 ) + 5
((10 ) + 5 ) *
((10 ) + 5 ) * 2

Just make sure that when deleting an operator to also delete the parentheses as well.

like image 100
Eiko Avatar answered Dec 19 '22 03:12

Eiko