Ok, so I started rethinking my project in terms of using straight C...
Here is a situation where I am a little unclear on what to do:
This code, takes a number and finds the closest value in an array:
+(NSUInteger)indexFor:(float)actual floats:(float *)floats
size:(NSUInteger)size {
if (actual < floats[0]) return 0;
for (int i = 1; i < size; i++) {
if (floats[i] > actual) {
float previous = floats[i - 1];
if (floats[i] - actual < actual - previous) {
return i;
} else {
return i - 1;
}
}
}
return size - 1;
}
--- tests ---
-(void)testItFindsTheClosestIndexGivenAnActualValueAndAListOfValues {
NSUInteger size = 2;
float floats[] = {1.0f, 2.0f};
subject = [ClosestValueFinder indexFor:1.25f floats:floats size:size];
XCTAssertEqual(subject, 0);
subject = [ClosestValueFinder indexFor:1.75f floats:floats size:size];
XCTAssertEqual(subject, 1);
floats[0] = 5.0f;
floats[1] = 6.0f;
subject = [ClosestValueFinder indexFor:-1.0f floats:floats size:size];
XCTAssertEqual(subject, 0);
subject = [ClosestValueFinder indexFor:8.0f floats:floats size:size];
XCTAssertEqual(subject, 1);
}
...
Cool, that all works fine and dandy. The problem doing it this way s that
sometimes I need this to work with an array of ints... NSNumber and NSArray
gave me the flexiblity of being able to use floats/ints and not have it matter.
Now, with this approach, I am not sure how to handle ints without having
another method with duplicate code.
Also, I thought I'd also bring up my lack of familiarity with C gives me some
confusion about how to pass arrays around.
So, if I understand correctly, if I have an array of a large size (not sure
what that means, or how large), I can't just do:
float floats[] = { ... }
I need to actually do
float *floats = (float *)malloc(size * sizeof(float));
and then I have to use &floats instead of floats?
[ClosestValueFinder indexFor:-1.0f floats:&floats size:size];
Is this a because it's on the "heap"?
Patrick J. Collins
http://collinatorstudios.com
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list ([email protected])
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/objc-language/archive%40mail-archive.com
This email sent to [email protected]