Confusing arrays - iphone

Kinda new to iOS, Im also studying Android. kinda confuse on arrays.
How to convert this into iOS:
result as being the index
nextresult[x] array of indexes
for(x = 0; x < array.size; x++)
{
if(result < nextresult[x])
nextresult[x] -= 1;
}
It will iccheck all of the content of the arrays if it needs to be adjusted or not,

Might be following will give you some idea -
As you mentioned, i have considered following - result' is value andnextresult` is array.
for(x = 0; x < [array count]; x++)
{
if(result < [nextresult objectAtIndex:x]) {
[nextresult objectAtIndex:x] -= 1;
}
}
EDIT -
if you want to add integer in arrays -
[yourArray addObject:[NSNumber numberWithInt:1]]; // Objective C array store objects. so we need to convert primitive data type into object.

Read Apple's excellent developer documentation.
You can find the docs about the NSArray class here, or in your Xcode organizer.
I have downvoted your question, because it could very easily have been solved by just looking at the docs.

Related

Create a NSPredicate to find elements whose length is > N

I have an array of strings ( more that 5k elements), each of variable length. I can use NSPredicate to find specific strings within the array( took a bit to figure that out). Now I need to find elements whose length is > than N.
I have looked through the documentation and Length does not seem to be one of the functions available in the Predicate Programming Guide.
Thanks in advance.
Imagmast
NSArray * words= [allLinedStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > %d",N]];
N is your integer as you mentioned in your question.
I'm not familiar with NSPredicate, so I can't give you a solution using it, but couldn't you just use some plain NSString methods:
//This is the length of the string you want to check
int threshold = 5;
//Iterates through all elements in the array
for(int index = 0; index < [stringArray count]; index++) {
//Checks if the length of the string stored at the current index is greater than N
if([[stringArray objectAtIndex:index] length] > threshold) {
//String length is greater than N
}
}
Optionally, you could add in a check to see if the array only has strings (sacrifices performance for safety) by replacing this line:
if([[stringArray objectAtIndex:index] length] > threshold)
With this:
if([[stringArray objectAtIndex:index] length] > threshold && [[stringArray objectAtIndex:index] isKindOfClass[NSString class]])
What this does is it makes sure that the object at the current index is an NSString. If it's not, you'd receive a runtime error.

Finding multiple numerations of a character in UITextView

I am a UITextView where I am trying to find the # character. The text view might have multiple #s, so I was wondering, how can I find the nth # character?
Currently, I have: NSRange range = [textViewText rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:#"#"]];. This only finds the first # instance. How can I find subsequent ones?
You could try doing something like splitting up the text based on #"#" and then you know where the components are split, thats where the # should appear. This way you can easily find the nth #
If I understand you question correctly, a regular expression would solve you problem.
RegEx has a bit of a learning curve but it comes in handy very often.
http://www.regular-expressions.info/
is a very good starting point for regular expressions in general
http://remarkablepixels.com/blog/2011/1/13/regular-expressions-on-ios-nsregularexpression.html
A tutorial about regular expression in iOS
http://reggyapp.com/
Reggy is an osx app in which you can test your RegEx on actual text.
What do you want to do once you've located the nth #?
Here's some sample code that sketches a solution. Not compiled or checked for bugs!
int targetItem = 3; // we find the 3rd item
NSString *workingStr = #"your#string#containing#stuff";
int foundAtLocation = -1;
for (int idx = 0; idx < targetItem; idx++) {
NSRange range = [workingStr rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:#"#"]];
if (range.location < 0) {
// not found, give up
foundAtLocation = -1;
break;
}
workingStr = [workingStr substringFromIndex:range.location];
foundAtLocation += range.location;
}
if (foundAtLocation >= 0) {
NSLog(#" I found the %d occurence of # at character index %d", targetItem, foundAtLocation);
}
else {
NSLog(#" Not found");
}

Objective-C += equivalent?

Sorry for the newbie question, but i cannot find an answer to it.
I have a simple operation. I declare a variable, and then i want to loop through an array of integers and add these to the variable. However, i can't seem to find how to get a += equivalent going in Objective C.
Any help would be awesome.
Code:
NSInteger * result;
for (NSInteger * hour in totalhours)
{
result += hour;
}
NSInteger is not a class, it's a typedef for int. You cannot put it into collections like NSArray directly.
You need to wrap your basic data types (int, char, BOOL, NSInteger (which expands to int)) into NSNumber objects to put them into collections.
NSInteger does work with +=, keep in mind that your code uses pointers to them, which is probably not what you want anyway here.
So
NSInteger a = 1, b = 2;
a += b;
would work.
If you put them with [NSNumber numberWitInt:a]; etc. into an NSArray, this is not that easy and you need to use -intValue methods to extract their values first.
If totalhours actually contains NSNumber objects you need the following:
NSInteger result = 0;
for(NSNumber* n in totalhours)
{
result += [n integerValue];
}
The problem is that you are confusing NSInteger (a typedef for int or long) with a class instance such as NSNumber.
If your totalhours object is an array of NSNumber objects, you'll need to do:
NSInteger result;
for (NSNumber *hour in totalhours)
{
result += [hour integerValue];
}
No problem using the '+=' operator, just be sure about the objects you are working with...
Your code might be :
NSNumber *n; NSUInteger t = 0;
for(n in totalHours) {
t += [n integerValue];
}
// you got your total in t...
The += operation definitly works. All you need to do is initialize your result variable so it has a start value.
E.g. NSInteger * result = 0;
Good luck!
Your problem is probably that you're using a pointer to an NSInteger instead of an actual NSInteger. You're also not initializing it. Try this:
NSInteger result = 0;
for (NSInteger * hour in totalhours)
{
result += *hour;
}

iPhone maths not quite adding up right

I am adding values held within an array but the sum is +1 what it actually should be.
//update totalscore
uint newTotalScore;
for (uint i=0; i< [bestscoresArray count] ; i++) {
newTotalScore += [[bestscoresArray objectAtIndex:i] intValue];
}
totalscore = newTotalScore;
//output
l1bestscore=15900, l2bestscore=7800, l3bestscore=81000, l4bestscore=81000, l5bestscore=0, l6bestscore=0, l7bestscore=0, l8bestscore=0, l9bestscore=0, l10bestscore=0, totalscore=185701
As you can see the totalscore output is 185701 but the sum of all values is 185700.
Would anyone have any ideas why this is occurring?
Thanks,
Mark
You must define newTotalScore's initial value:
uint newTotalScore = 0;
Otherwise it will be undefined. In your case it was 1 but it could have been any other value.
Not sure about this, but did you try initializing newTotalScore to zero? (See this question about variable initialization.) If that does not help, give us more code.

Using a C function in Objective-C (for iPhone)

'lo all. I am a self-described admitted noob in iPhone programming (having a much longer perl & web background -- 30 years)...but took the plunge last week and bought a couple of good books. After cramming and reading well over 1000 pages -- and understanding it pretty well, I am well on my way to a good first Native iPhone app. My problem is this: I do not know how to do a simple Geographic (lat/long) point-in-polygon routine in Objective-C. I have 2 ways of doing this. One in C (the first code example) and one in JavaScript (the second code example):
// this is the poly.h file
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy);
// this is the poly.c file
#include "poly.h"
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy){
int i, j, c = 0;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) &&
(testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}
or this (in Javascript):
function _isPointInPoly(poly, pt){
for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
&& (c = !c);
return c;
}
(either one will work if i could get them converted)
So, to try this out...I put the .h file and .c file into xcode with my iPhone project. The only question now is how to call this from Objective-C and get the result.. :)
BTW: I searched the Great God Google all last night to get the answer to this but just TRY to search for "including C in an Objective-C iPhone app", etc.. you get so many entries and none have to do with this! :) Just letting you know I tried google before posting here.
Okay, my issues:
How do I call the pnpoly from Objective-C?
What types do i call it using? (int is fine, but the float
*vertx is obviously an array of floats..which NSArray does not have
-- that I can find)
(EDIT: HERE IS MORE INFO. I AM ASKING FOR HELP CONTRUCTING THE ARRAYS THAT WOULD BE PASSED AS WELL)
The question was not asked fully.
The routine (in objective-c) would be like this: (assuming this is coded right)
NSMutableArray *latitudeArray = [[NSMutableArray alloc] init];
NSMutableArray *longitudeArray = [[NSMutableArray alloc] init];
// coordinates surrounding 1 inifite loop.
[latitudeArray addObject:#"37.32812557141369"];
[longitudeArray addObject:#"-122.0320253896318"];
[latitudeArray addObject:#"37.32821852349916"];
[longitudeArray addObject:#"-122.0289014325174"];
[latitudeArray addObject:#"37.33021046381746"];
[longitudeArray addObject:#"-122.0289300638158"];
[latitudeArray addObject:#"37.33042111092124"];
[longitudeArray addObject:#"-122.0279574092159"];
[latitudeArray addObject:#"37.33395972491337"];
[longitudeArray addObject:#"-122.0279263955651"];
[latitudeArray addObject:#"37.33363270879559"];
[longitudeArray addObject:#"-122.0320527775551"];
[latitudeArray addObject:#"37.32812557141369"];
[longitudeArray addObject:#"-122.0320253896318"];
int nvert = [[latitudeArray count] intvalue];
// 37.33189399206268 x -122.0296274412866 should return true
float testx =37.33189399206268;
float testy =-122.0296274412866;
int y_or_n = pnpoly(int nvert, float *vertx, float *verty, float testx, float testy);
I should've made it clear that I am learning Objective-c but FOUND that C routine--so was not sure how to construct either the C variables to call it with or the routine to call it with.
I know this is asking a lot...but it is really puzzling to me. Can anyone help me?
Thanks so much.
Jann
You can just call it. Objective-C is just a front-end to a C API and a way of re-writing methods as functions (to some approximation, anyway...) so you can call a C function just as you would in C code.
- (int)doWhatever {
// ...
int hitTest = pnPoly(/*blah*/);
return hitTest;
}
You can use C primitive types like int and float in Objective-C without issue, too. So call the function with floats :). If you need to store such values in Foundation collection classes like NSArray, then you can wrap them in a class called NSNumber.
NSNumber *someFloat = [NSNumber numberWithFloat: f];
float usefulValue = [someFloat floatValue];
Here's en example of how it would be used:
int nCoords = 4;
float vertexXCoords[n] = {0.0, 0.0, 20.0, 20.0};
float vertexYCoords[n] = {0.0, 20.0, 20.0, 0.0};
NSPoint testPoint = NSMakePoint(5, 10);
BOOL testPointIsInPoly = pnpoly(nCoords, xCoords, yCoords, testPoint.x, testPoint.y);
Note that there's nothing specific to Objective-C in here. This is C code (though it does use the Cocoa BOOL and NSPoint C types). Since Objective-C is a strict superset of C, any valid C code is also valid Objective-C. This is also a case in which Objective-C's unique features would not be particularly useful. (Numerical calculations in general are less complex and more readable in plain C.)
objective C is a superset of C, so you can call C routines. If you are calling that routine a lot, inline it or make it a macro.