I have an array of indices [1 … 20]. The first 4 elements of the indicesArray are linked to a file of a certain type (call it type A), the other 16 are linked to type B.
I shuffle the array at random. I now wish to extract 4 of the indices but at most only one of the 4 can be of type A.
I think I need to use the enum function here to define indices 1-4 as “type A” & indices 5-20 as “type B”, then if I looked at e.g. the first element of my freshly randomised indicesArray[0] I could tell which type it is & act accordingly.
The way I’ve seen enum used from examples it goes something like:
enum category { typeA = 0, typeB };
Is it possible to assign indices 1-4 to typeA & the rest to typeB, or am I on the wrong track here? thanks in advance.
Edit to include code snippet
I tried to test this & ran into an error right away
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int* indices = malloc(20*sizeof(int));
for (int i=0; i<20; i++) {
indices[i] = i;
}
enum category {typeA, typeB};
enum category categoryForIndex(int index) {
if (index >= 1 && index <= 4) {
return typeA;
} else {
return typeB;
}
}
[pool drain];
return 0;
}
When i try to compile this I get the error “nested functions are disabled, use -fnested-functions to re-enable”, which usually happens when a second main gets thrown into the mix by accident, or someething like that. Any ideas?
Edit to include some code which shows how to put the solution into practice
#import <Foundation/Foundation.h>
enum category {typeA, typeB};
enum category categoryForIndex(int index) {
if (index >= 1 && index <= 4) {
return typeA;
} else {
return typeB;
}
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int* indices = malloc(20*sizeof(int));
for (int i=1; i<=20; i++) {
indices[i] = i;
}
NSLog(@"index[0] is %i:", indices[16]);
enum category index;
index = indices[16];
switch (categoryForIndex(index)) { //this tests to see what category 16 belongs to
case typeA:
NSLog(@"index is of type A");
break;
case typeB:
NSLog(@"index is of type B");
break;
default:
NSLog(@"index not valid");
break;
}
[pool drain];
return 0;
}
You’re off track. You cannot assign 1-4 a given enum. Enum constants have precisely one value, and only one. What you can do is use an enum to define two types, say
typeAandtypeBas you’ve already done, and then define a function that maps an index back to a type, e.g.Now you have a way to categorize your indexes.