Why does NSMutablearray keep returning null? - objective-c

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

NSLog(#"The content of array is%#",[equation randEquation]);
Based on your code, for this log to output The content of array is(null) means that equation is nil. Your randEquation (while not efficient) looks ok, the problem is that you haven't created the equation instance when you run the log statement.

Related

How to convert NSString intoNSArray?

I have an NSString which is a mathematical expression. I have operators (+,-,*,/) and operands (digits from 0 to 9,integers,decimals etc). I want to convert this NSString into NSArray. For example if my NSString is "7.9999-1.234*-9.21". I want NSArray having elements 7.9999,-,1.234,*,-,9.21 in the same order. How can I accomplish this?
I have tried a code. It dosent work in all scenarios though. Here It is:
code:
NSString *str=#"7.9999-1.234*-9.21";
NSMutableArray *marray=[[NSMutableArray alloc] init];
for(i=0;i<6;i++)
{
[marray addObject:[NSNull null]];
}
NSMutableArray *operands=[[NSMutableArray alloc] initWithObjects:#"7.9999",#"1.234",#"9.21",nil];
NSMutableArray *operators=[[NSMutableArray alloc] initWithObjects:#"-",#"*",#"-",nil];
for(i=0,j=0,k=0,l=0;i<=([str length]-1),j<[operands count],k<[operators count],l<[marray count];i++)
{
NSString *element=[[NSString alloc] initWithFormat:#"%c",[str characterAtIndex:i]];
BOOL res=[element isEqualToString:#"+"]||[element isEqualToString:#"-"]||[element isEqualToString:#"*"]||[element isEqualToString:#"/"];
if(res==0)
{
[marray replaceObjectAtIndex:l withObject:[operands objectAtIndex:j]];
}
else
{
l++;
[marray replaceObjectAtIndex:l withObject:[operators objectAtIndex:k]];
k++,l++,j++;
}
}
for(i=0;i<6;i++)
{
NSLog(#"%#",[marray objectAtIndex:i]);
}
Here str is the string to be converted. My array is the array obtained by converting the string str. When I execute this code I get the following on console:
7.9999
-
1.234
*
<null>
-
You should use NSScanner, scanning up to your operator characters, then when you find one, save the scanned string and then save the operator into the array and skip the operator (setScanLocation:). Continue doing this till you get to the end of the string (in a loop, one iteration for each operator).
NSArray * marray = [str componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"+-*/"]
];
ThankYou #Wain and #Hinata Hyuga.I figured out a code that would work to convert any string to array with the help of your suggestions.
Here is the code
NSMutableArray *convArray=[[NSMutableArray alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:inputString];
NSCharacterSet *opSet=[NSCharacterSet characterSetWithCharactersInString:#"+-/*"];
[scanner setCharactersToBeSkipped:opSet];
int i;
for(i=0;i<[inputString length];)
{
if([inputString characterAtIndex:i]=='+'||[inputString characterAtIndex:i]=='-'||[inputString characterAtIndex:i]=='*'||[inputString characterAtIndex:i]=='/')
{
[convArray addObject:[[NSString alloc] initWithFormat:#"%c",[inputString characterAtIndex:i]]];
i++;
}
else
{
NSString *oprnd;
[scanner scanUpToCharactersFromSet:opSet intoString:&oprnd];
[convArray addObject:oprnd];
i=i+[inputString rangeOfString:oprnd].length;
}
}
return convArray;

Part of NSString to NSNumber

I need to input x and y co-ordinates into a custom object, the input is with the format "x,y"
I am currently storing the input as an NSString and need to get the integers out of it and into separate NSNumbers. If there is another way to store the input that would be easier, please explain.
I need to store x and y as separate NSNumbers, this also this needs to account for if x and y are 2 digits. i.e. "23,4"
can anyone help?
Use -[NSString componentsSeparatedByString:]
NSArray *numericComponents = [string componentsSeparatedByString:#","];
NSArray *numbers = [numericComponents map:^id(NSString *object) {
return #([object integerValue]);
}];
map here is simply a category method that I've added to NSArray:
#implementation NSArray (JRAdditions)
- (NSArray *)map:(id(^)(id))block {
if([self count] == 0 || block == nil) return self;
NSMutableArray *mapped = [NSMutableArray new];
NSArray *copy = [self copy];
for(id obj in copy) {
id mappedObject = block(obj);
if(mappedObject) {
[mapped addObject:mappedObject];
}
}
return [mapped copy];
}
#end
NSString *str=#"23,4";
NSArray *array=[str componentsSeparatedByString:#","];
NSNumber *xNum=#([array[0] integerValue]);
NSNumber *yNum=#([array[1] integerValue]);
To check if they are two digits :
if ([xNum integerValue]>9 && [xNum integerValue]<100) {
NSLog(#"x is 2 digits");
}
else{
}
if([yNum integerValue]>9 && [yNum integerValue]<100) {
NSLog(#"y is 2 digits");
}
else{
}

Array of floating point values in Objective-C

How can I create array of floating point numbers in Objective-C?
Is it possible?
You can create a dynamic array (size decided at runtime, not compile time) in different ways, depending on the language you wish to use:
Objective-C
NSArray *array = [[NSArray alloc] initWithObjects:
[NSNumber numberWithFloat:1.0f],
[NSNumber numberWithFloat:2.0f],
[NSNumber numberWithFloat:3.0f],
nil];
...
[array release]; // If you aren't using ARC
or, if you want to change it after creating it, use an NSMutableArray:
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array addObject:[NSNumber numberWithFloat:2.0f]];
[array addObject:[NSNumber numberWithFloat:3.0f]];
...
[array replaceObjectAtIndex:1 withObject:[NSNumber numberWithFloat:99.9f]];
...
[array release]; // If you aren't using ARC
Or using the new-ish Objective-C literals syntax:
NSArray *array = #[ #1.0f, #2.0f, #3.0f ];
...
[array release]; // If you aren't using ARC
C
float *array = (float *)malloc(sizeof(float) * 3);
array[0] = 1.0f;
array[1] = 2.0f;
array[2] = 3.0f;
...
free(array);
C++ / Objective-C++
std::vector<float> array;
array[0] = 1.0f;
array[1] = 2.0f;
array[2] = 3.0f;
For an dynamic approach you can use NSNumber object and add it to NSMutableArray, or if you need only static array then use suggestions from comments, or use standard C.
like:
NSMutableArray *yourArray = [NSMutableArray array];
float yourFloat = 5.55;
NSNumber *yourFloatNumber = [NSNumer numberWithFloat:yourFloat];
[yourArray addObject:yourFloatNumber];
and then to retrive:
NSNumber *yourFloatNumber = [yourArray objectAtIndex:0]
float yourFloat = [yourFloatNumber floatValue];
If you are using Xcode 4.4+, you can try this:
NSArray *a = #[ #1.1f, #2.2f, #3.3f];
Here is all new literals of LLVM Compiler 4.0.
How about something like this?
#interface DoubleArray : NSObject
#property(readonly, nonatomic) NSUInteger count;
#property(readonly, nonatomic) double *buffer;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithCount:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
- (double)valueAtIndex:(NSUInteger)idx;
- (void)setValue:(double)value atIndex:(NSUInteger)idx;
#end
#implementation DoubleArray
- (void)dealloc
{
if (_buffer != 0) {
free(_buffer);
}
}
- (instancetype)initWithCount:(NSUInteger)count
{
self = [super init];
if (self) {
_count = count;
_buffer = calloc(rows * columns, sizeof(double));
}
return self;
}
- (double)valueAtIndex:(NSUInteger)idx
{
return *(_buffer + idx);
}
- (void)setValue:(double)value atIndex:(NSUInteger)idx
{
*(_buffer + idx) = value;
}
#end
It's a basic array. You can extend this with more complex features like appending, indexed removal etc.

Difficulty with getting random words from NSArray

When I Build & Run my application, it will not generate anything. What I have generating are words and after it erases that word and continues until it exhausts all the words and then repopulates the list again. Here is the code:
#implementation randomnumbersViewController
#synthesize words;
#synthesize randomArray;
#synthesize array;
-(IBAction)generateNumber:(id)sender {
NSInteger randomize(id num1, id num2, void *context);
int rand = arc4random() %2;
if (rand)
return NSOrderedAscending;
else
return NSOrderedDescending;
}
- (void)resetRandomArray;
{
[randomArray setArray: array];
[randomArray sortUsingFunction:random context:NULL];
}
- (NSString*) getRandomWord; {
if ([randomArray count] ==0)
return nil;
NSString* result;
NSInteger randomIndex = [[randomArray lastObject] intValue];
[randomArray removeLastObject];
result = [words objectAtIndex:randomIndex];
return result;
}
- (void)buildRandomWordArray
{
NSInteger index;
NSError *theError;
NSString *path = [[NSBundle mainBundle] pathForResource:#"words" ofType:#"text"];
NSString *text = [NSString stringWithContentsOfFile: path
encoding: NSUTF8StringEncoding
error: &theError];
self.words = [text componentsSeparatedByString: #"\n"];
int arraySize = [words count];
self.array = [NSMutableArray arrayWithCapacity:arraySize];
//This code fills "array' with index values from 0 to the number of elements in the "words" array.
for (index = 0; index<arraySize; index++)
[array addObject: [NSNumber numberWithInt: index]];
[self resetRandomArray];
//for (index = 0; index<=arraySize; index++)
// NSLog(# "Random word: %#", [self getRandomWord]);
}
Also a .txt document must be included in the resources folder in for this to work and I do have it there, but nothing. Does anyone have any suggestions as to how I can actually get it to generate the words, or why it isn't working properly?
I don't get how sorting the array ascending or descending is going to shuffle the array, maybe because it doesn't. :) You should use the Fisher–Yates shuffle implemented here: What's the Best Way to Shuffle an NSMutableArray? Import that category, and just call shuffle on the mutable array.

Method Creates an Array with 11 objects, All Out of Scope, Unrecognized Selector Results

Okay, so, I'm doing a simple lookup. I have an array of NSString objects and a string to search for in the array's elements.
It all seems to work up until I try to add a match to a new mutable array made to hold the search results. The stringHolder variable gets the string, and resultsCollectorArray even get the right number of new elements, but each element is empty and "out of range". Here's the method:
#implementation NSArray (checkForString)
-(NSMutableArray *) checkForString: (NSString *) matchSought
{
long unsigned numberofArrayElements;
long unsigned loop = 0;
NSRange searchResults;
NSMutableArray * resultCollectorArray = [[NSMutableSet alloc] init];
id stringHolder;
numberofArrayElements = [self count];
while (loop < numberofArrayElements) {
searchResults.length = 0;
searchResults = [[self objectAtIndex: loop] rangeOfString: matchSought options:NSCaseInsensitiveSearch];
if (searchResults.length > 0) {
stringHolder = [self objectAtIndex: loop];
[resultCollectorArray addObject: stringHolder];
}
loop++;
}
return [resultCollectorArray autorelease];
}
Once we get back to the main portion of the program, I get an unrecognized selector sent to the mutable array that was supposed to receive the result of the method. Here's the main section:
#import <Foundation/Foundation.h>
#import "LookupInArray.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *testString = [[NSString alloc] initWithString: #"ab"];
NSMutableString * resultString = [[NSString alloc] init];
NSArray * theArray = [[NSArray alloc] initWithObjects: ..., nil]; // Actual code has the objects
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSUInteger arrayCount = 0;
unsigned long loops = 0;
resultArray = [theArray checkForString: testString];
arrayCount = [resultArray count];
while (loops < arrayCount){
resultString = [resultArray objectAtIndex: loops]; // Here's where we get the unrecognized selector.
NSLog(#"%#", resultString);
loops++;
}
[pool drain]; // Also, I'll release the objects later. I just want to get what's above working first.
return 0;
}
I've searched the other answers (for hours now), but didn't seen anything that solved the issue.
Any and all help would be really appreciated.
And thanks beforehand.
NSMutableArray * resultCollectorArray = [[NSMutableSet alloc] init]; is so incorrect. You are creating a mutable set and assigning it to a mutable array.
You are getting unrecognized selector because objectAtIndex: is not a valid selector for NSMutableSet. Make that statement,
NSMutableArray * resultCollectorArray = [[NSMutableArray alloc] init];
A Better way
NSArray * filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF contains[cd] %#", searchString]];
You can directly filter the array using predicates. This way you do this in a single step. :)