how to get the index on numbers generated by int arc4random() - objective-c

How do you get the index of the number appearing from the arc4rand method?. If 4,1,2,3 appear how do you index them . Example 4 would be 0 in the array.
int rand=((arc4random()%4)+1);

For getting random number, i did like this:
Suppose, i have a mutable array
NSMutableArray * myArray = [[NSMutableArray alloc] init];
and i kept 5 data in this myArray.
Now I have to generate random number index from myArray.
int randomIndex = (arc4random() % ([myArray count]));
Here randomIndex is random index of array

try this one. you need to put all that values into array.
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:4];
[array insertObject:#"4" atIndex:0];
[array insertObject:#"1" atIndex:1];
[array insertObject:#"2" atIndex:2];
[array insertObject:#"3" atIndex:3];

using array to get index in ios to add all values in array like this
//convert int to nsstring and add array
NSArray *array=[NSArray arrayWithObjects:NSStringFromInt(4),NSStringFromInt(1),NSStringFromInt(2),NSStringFromInt(3), nil];
//reverse process to get int value
int value=[[array objectAtIndex:index]integerValue];

I'm just guessing, you might look for this...
NSMutableArray *_array = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
[_array addObject:#((arc4random()%4)+1)];
}

Related

Auto increasing numbers in array

i'm just starting out with Xcode and need some help. I have this array set up:
myArray = [NSMutableArray arrayWithObjects: item1type1, item1type, item1type3, item1type4, item1type5, item1type6, item1type7, item1type8, item1type9, nil];
Is it possible to auto-assign numbers to elements in a sequence? The logic is simple: item1type(i), item1type(i+1), item1type(i+2),...
Many thanks
There are too many magic numbers in this code, but here you go:
// Build an Array of keys #[#"item_1_type_1", #"item_1_type_2", ..., #"item_1_type_9"] programmatically
const int numberOfElements = 9;
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:numberOfElements];
for (int i = 1; i <= numberOfElements; i++) {
[keys addObject:[NSString stringWithFormat:#"item_1_type_%d", i]];
}
// Extract chosen keys from JSON Dictionary into an Array, matching the
// order of the keys above.
NSDictionary *subDict = myJSONData[#"item1"];
NSArray *myArray = [subDict objectsForKeys:keys notFoundMarker:[NSNull null]];

Populating array with integers

Let's say I want to populate NSarray with 50 integers. We know that NSarray accept only objects. So I have to do 50 times
NSNumber *num1 = [NSNumber numberWithInit:10];
NSNumber *num2 = [NSNumber numberWithInit:212];
......
NSNumber *num50 = [NSNumber numberWithInit:12];
Is there more elegant way to achieve that, beacause looks stupid 50 lines of code only for create number objects ?
try this...
NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:50 ];
for (int i=0; i<0; i++) {
NSNumber *number=[[NSNumber alloc] initWithInt:i];
[array addObject:number];
[number release];
}
//do anything with arrray and release the array later.
is this OK or you are seeking anything else.?
How about using NSMutableArray?
NSMutableArray* arr = [[NSMutableArray alloc] init];
int i = 0;
for(i=0; i<50; i++) {
NSNumber* num = [NSNumber numberWithInt:i]; // use i or random numbers
[arr addObject:num];
}
Your numbers do not seem to follow any particular pattern, so you might be better doing this by creating a C array first:
int myValues[] = { 10, 212, ..., 12 };
NSUInteger count = sizeof(myValues)/sizeof(int); // number of integers in myValues
// abstract the following into a function/method/category if doing more than once
NSMutableArray *objcValues = [NSMutableArray arrayWithCapacity:count];
for(NSUInteger ix = 0; ix < count; ix++)
[objcValues addObject:[NSNumber numberWithInt:myValues[ix]];

How to locate maximum value and position in NSMutableArray

I need to search a mutable array for the maximum value and return its position as well as value. I'd only like to iterate through the array once and I'm not sure if that's possible
an example of what I'm trying to accomplish can be demonstrated below
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i<20; i++)
[array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];
NSObject *max = [array valueForKeyPath:#"#max.self"];
the max object only seems to contain the value (and not the position). this can be demonstrated through the debugger with print-object max
Any advice out there?
Using valueForKeyPath:#"#max.self" is great, but only if you want the maximum value.
To know both index and value in one iteration, I'd use enumerateWithBlock:
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i<20; i++)
[array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];
__block NSUInteger maxIndex;
__block NSNumber* maxValue = [NSNumber numberWithFloat:0];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSNumber* newValue = obj;
if ([newValue isGreaterThan:maxValue]) {
maxValue = newValue;
maxIndex = idx;
}
}];
Quite more code, but you're iterating only once in the array.
If you're not worried about the possibility of there being more than one identical maximum value in the array, you can use -indexOfObject: to get the index. It will return the first occurrence of the object in the array.
NSUInteger index = [array indexOfObject:max];
I hope, following solution will help you to identify maximum value from array.
int max = [[numberArray valueForKeyPath:#"#max.intValue"] intValue];
NSLog(#"Highest number: %i",max);
Please let me know if any issue.
Here you can find correct way to deal with collections and KVC
Its nice Post by Matt
http://nshipster.com/kvc-collection-operators/

Creating a NSArray from a C Array

There are many threads about going the opposite way, but I am interested in converting from a primitive C array to a NSArray. The reason for this is that I want to create a NSString from the array contents. To create the NSString I will use:
NSArray *array;
NSString *stringFromArray = [array componentsJoinedByString:#","];
I am joining the elements of the array by commas because I will later be saving the string as a .csv file. I don't think it matters, but the C array I am dealing with is of type double and size 43.
double c_array = new double [43];
Thanks!
NSString * stringFromArray = NULL;
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity: 43];
if(array)
{
NSInteger count = 0;
while( count++ < 43 )
{
[array addObject: [NSString stringWithFormat: #"%f", c_array[count]]];
}
stringFromArray = [array componentsJoinedByString:#","];
[array release];
}

Create multiple numbered variables based on a int

How would I create a number of NSDictionary variables using an array's count?
This is basically what I came up with, but I'm not sure how to make this work with Objective-C syntax. doesntContainAnother is an NSArray. I want the names of the dictionaries to use the current value of loopInt.
int *loopInt = 0;
while (doesntContainAnother.count <= loopInt) {
NSMutableDictionary *[NSString stringWithFormat:#"loopDictionary%i", loopInt] = [[[NSMutableDictionary alloc] init] autorelease];
[NSString stringWithFormat:#"loopDictionary%i", loopInt] = [NSDictionary dictionaryWithObject:[array1 objectAtIndex:loopInt]
forKey:[array2 objectAtIndex:loopInt]];
loopInt = loopInt + 1;
}
Create a mutable array and loop until you reach the original array's count, creating a dictionary and adding it to the mutable array on each iteration.
Your code should look like this.
NSMutableArray *dictionaries = [[NSMutableArray alloc] init];
for (int i = 0; i < doesntContainAnother.count; i++) {
[dictionaries addObject:[NSMutableDictionary dictionaryWithObject:[array1 objectAtIndex:i] forKey:[array2 objectAtIndex:i]]];
}
The approach of creating variables with numbers at the end of their names is an antipattern and not even possible in Objective-C. It's equivalent to an array, but clunkier.
You need to create a mutable array, and then put the objects into the array. You can't create a variable with the same name as the contents of a string, as you have done. For example:
NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[doesntContainAnother count]];
int i = 0; // Note: type is int, not int*
for (i = 0; i < [doesntCountainAnother count]; i++) {
[arr addObject:[NSMutableDictionary dictionary]];
}
// Later...
NSMutableDictionary *d1 = [arr objectAtIndex:3];
Or if you want to pull them out of the list by name:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:[doesntCountainAnother count]];
int i = 0;
for (i = 0; i < [doesntContainAnother count]; i++) {
[dict setObject:[NSMutableDictionary dictionary] forKey:[NSString stringWithFormat:#"loopDictionary%d", i]];
}
// Later...
NSMutableDictionary *d1 = [dict objectForKey:#"loopDictionary3"];
But the first way is likely the easiest.