I am generating a random equation say like 2*3+4..... and using DDMathparser to evaluate it. Here I have a class method which is supposed to return a random equation(stored inside a mutable array) only if it evaluates to a integer. however it keeps returning Null and i can't figure out why. Please help me out.!
#import "Equation.h"
#import "DDMathParser.h"
@implementation Equation
-(NSMutableArray*)randEquation{
NSMutableArray* usableEquation=[[NSMutableArray alloc]init];
while(1){
NSArray *nums = @[@"1", @"2", @"3", @"4", @"5",@"6",@"7",@"8",@"9"];
unsigned index1=arc4random()%9;
NSString* num = [NSString stringWithFormat:@"%@", [nums objectAtIndex:index1]];
NSArray *symbols = @[@"+", @"-", @"*", @"/"];
unsigned index=arc4random()%4;
NSString* symb = [NSString stringWithFormat:@"%@", [symbols objectAtIndex:index]];
NSMutableArray *arrayOfSymbolsAndNumbers = [[NSMutableArray alloc] init];
for( int i=0;i<=10;i++){
if (i%2==0) {
[arrayOfSymbolsAndNumbers addObject:num];
}
else{
[arrayOfSymbolsAndNumbers addObject:symb];
}
}
NSMutableString *stringOfSymbolsAndNumbers=[[NSMutableString alloc]init];
for (NSObject * obj in arrayOfSymbolsAndNumbers)
{
[stringOfSymbolsAndNumbers appendString:[obj description]];
}
usableEquation=arrayOfSymbolsAndNumbers;
NSNumber *result=[stringOfSymbolsAndNumbers numberByEvaluatingString];
float resultFloat = [result floatValue];
float checker=resultFloat;
if (floor(checker)==checker) {
break;
}
else{
continue;
}
}
return usableEquation;
}
@end
Based on your code, for this log to output
The content of array is(null)
means thatequation
is nil. YourrandEquation
(while not efficient) looks ok, the problem is that you haven't created theequation
instance when you run the log statement.