NSMutableArray Initialization at multiple indexes - ios

Trying to create an array to store data about a deck of cards.
I'm wanting to keep a boolean for each card.
I want to create an array of capacity 52 with each index initialized to NO (or 0). Is there a way to do this all in one go instead of
[[NSArray alloc] initWithObjects: 0, 0, 0, .... nil];

Either put all 52 instances of #NO as parameters to initWithObject: or create it as an NSMutableArray and use a loop to add 52 objects.
NSMutableArray *array = [NSMutableArray arrayWithCapacity:52];
for (int i = 0; i < 52; i++) {
[array addObject:#NO];
}
BTW - passing a set of 0 to initWithObjects: won't work at all. Either use #NO for the BOOL value of NO or use #0 for the number 0 (wrapped as an NSNumber). Just using 0 is the same as nil so no objects will be added.

Use a loop
NSMutableArray *deck = [NSMutableArray array];
for(NSInteger i = 0; i < 52; i++)
{
[deck addObject:[NSNumber numberWithInteger:0]];
}

Related

Added NSMutableArray elements into another NSMutableArray in jumble way

I have NSMutableArray of 100 elements in it.
I want to load "20 - 50", "10 - 20", "60 - 100" and 50 - 60. elements into separate NSMutableArray and its Index value into another NSMutableArray.
is there away I can load 20 - 50 elements 30 count items after the 10 - 20 elements 10 count items then 60 - 100 items i.e 40 count finally 50 - 60 items 10 count items added into one new NSmutableArray and there index storied value into another NSmutableArray.
Is there a way i can add the items
NSMutableArray *valueArray; // Value array count is 100.
NSMutableArray *indexValue;
NSMutableArray *addValueRangeArray;
for (int i = 0; i< [ valueArray count ]; i ++) {
if (i == 20 && i <= 50 )
{
[addValueRangeArray addObject:[valueArray objectAtIndex:i]];
[indexValue addObject:i];
}
}
Here its not working since for count loop starts 0 to 99
and items added starts from 0
I want to added item with range base where i do get objects added and also the index value too.
Your input are highly appreciated
Let me know if not understand the question.
Since its tricky one.
You can use subarrayWithRange to get specific range from array.
if (valueArray.count >= 100) {
NSMutableArray *rangeArray = [[NSMutableArray alloc] init];
[rangeArray addObjectsFromArray:[valueArray subarrayWithRange:NSMakeRange(20, 30)]];
//and so on.
}
Note: With NSMakeRange passed first parameter as range's starting point and second one is length so pass the number of objects for that range, so for first range 20-50 it is NSMakeRange(20, 30). It may cause you crash if your valueArray doesn't have objects with that range.
You can do it like this
NSArray *arr = [NSArray arrayWithObjects:#"Temp1",#"Temp2",#"Temp3",#"Temp4",#"Temp5",#"Temp6",#"Temp7",#"Temp8",#"Temp9",#"Temp10",#"Temp11",#"Temp12",#"Temp13",#"Temp14",#"Temp15",#"Temp16",#"Temp17",#"Temp18", nil];
// Here create an array of your ranges through which you want your data
NSArray *arrIndex = [NSArray arrayWithObjects:[NSValue valueWithRange:NSMakeRange(3,4)],[NSValue valueWithRange:NSMakeRange(0,4)],[NSValue valueWithRange:NSMakeRange(11,7)],[NSValue valueWithRange:NSMakeRange(7,4)], nil];
NSMutableArray *arrTemp = [NSMutableArray new];
for (int i=0;i<arrIndex.count;i++) {
[arrTemp addObject:[arr subarrayWithRange:[arrIndex[i] rangeValue]]];
}
for (NSArray *arr in arrTemp) {
NSLog(#"Arra - %#",arr);
}
As per your question your range would be
NSArray *arrIndex = [NSArray arrayWithObjects:[NSValue valueWithRange:NSMakeRange(20,30)],[NSValue valueWithRange:NSMakeRange(10,10)],[NSValue valueWithRange:NSMakeRange(60,40)],[NSValue valueWithRange:NSMakeRange(50,10)], nil];

Sort NSArray in descending order

I have an NSArray with 4 objects, let's say 1, 2, 3 and 4. I want to sort this array in ascending order, but with a randomly selected starting number. For instance; 2, 3, 4 and 1 or 4, 1, 2 and 3.
How can I do this?
What I have thus far:
NSArray *playersArray = [_players allKeys];
NSSortDescriptor *sortPlayerArray = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
playersArray = [playersArray sortedArrayUsingDescriptors:#[sortPlayerArray]];
This results in 1, 2, 3, 4, obviously. I am also able to randomly order the players, like so:
activePlayersArray = [_players allKeys];
NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:activePlayersArray];
int count = (int)[temp count];
for (int i = 0; i < count; ++i) {
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[temp exchangeObjectAtIndex:i withObjectAtIndex:n];
}
activePlayersArray = [NSArray arrayWithArray:temp];
So how can I "combine" these two to get the results I want?
Hope you guys can help me.
Thanks!
This is really an algorithm problem, not an iOS problem. Here are the steps to follow
make a note of your randomly selected number
Sort the array in descending order as you normally would (as in Sort an NSArray in Descending Order)
Then split the array at the location of your special number (similar to How to split an NSArray into two equal pieces?)
after the split create a new array where the second piece now comes first
Another solution is to create a circular array of sorted elements and then traverse the array in reverse order.
I think this is what #Konsol intends, with a couple fixes: (1) it looks like the OP wants the order to be ascending, and (2) the array split in the other answer is at the midpoint. But I think the spirit is correct...
// Start with an unsorted (immutable?) input array of numbers (or any object
// that implements compare:.
// Pick a random location and produce an output array as described by the OP
NSMutableArray *mutableArray = [inputArray mutableCopy]; // if its not mutable already
[mutableArray sortUsingSelector:#selector(compare:)];
NSInteger inputIndex=arc4random_uniform(mutableArray.count);
NSArray *start = [mutableArray subarrayWithRange:NSMakeRange(inputIndex, mutableArray.count-inputIndex)];
NSArray *end = [mutableArray subarrayWithRange:NSMakeRange(0, inputIndex)];
NSArray *outputArray = [start arrayByAddingObjectsFromArray:end];
NSLog(#"%#", outputArray);
int count = (int)[activePlayersArray count];
int n = (arc4random() % nElements) + i;
NSMutableArray *temp = [[NSMutableArray alloc] init];
for (int i = 0; i < count; ++i) {
int nElements = count - i;
[temp addObject:[activePlayersArray objectAtIndex:(n-i)%count]];
}
activePlayersArray = [NSArray arrayWithArray:temp];
Hope it works!

Iterating through an NSArray and storing items in groups of 12

I've definitely tried to do my due diligence on this one but keep coming up short. I have an array of objects that I have parsed and I want to iterate through these and store them. Assuming the array is 144 objects (just an example), I want to store it in groups of 12 to display in a tableview cell. Actually of those 12 objects in the array I'll likely only be displaying 3-4 in the cell, but all of those objects in the detail view.
To help explain what I mean (sorry if it hasn't made sense at this point) here's some of the code I've got that is getting the data.
NSMutableArray *objectsArray = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in objectsNode) {
PHSingleEvent *singleEvent = [[PHSingleEvent alloc]init];
[objectsArray addObject:singleEvent];
singleEvent.title = [[element firstChild] content];
}
This pulls down the entire array of objects (an unknown number but definitely a multiple of 12). How would I go about storing 12 objects at a time into a single event?
I can log the info with
PHSingleEvent *firstObject = [objectsArray objectAtIndex:0] // this one is null
PHSingleEvent *eventStartTime = [objectsArray objectAtIndex:1];
PHSingleEvent *eventEndTime = [objectsArray objectAtIndex:2];
...
PHSingleEvent *lastObject = [objectsArray objectAtIndex:11];
NSLog(#"single object of event: %#", eventStartTime.startTime);
NSLog(#"single object of event: %#", eventEndTime.endTime);
etc...
But the array keeps going past 12. I want to iterate up through each 12 objects and store those values, preferably as strings to be displayed in a cell and detail view.
Any ideas?
Thanks much in advance and I will be here to answer any questions if I was unclear.
C.
How about using a for loop? Assuming that each event object has 12 sub-objects (i.e. indices 0 - 11) you could achieve storing it by using a mod function. For example:
NSMutableArray *eventArray = [[NSMutableArray alloc] init];
for(int i=0; i<objectArray.count/12;i++){
int offset = 12*i;
NSMutableArray *event = [objectsArray subarrayWithRange:NSMakeRange(offset, 12)];
[eventArray addObject:event];
}
So now eventArray has n arrays, each of 12 objects (where n = totalObjects/12)
EDIT: A better idea would be to use NSDictionary. For example:
NSMutableArray *eventArray = [[NSMutableArray alloc] init];
for(int i=0; i<objectArray.count/12;i++){
int offset = 12*i;
NSDictionary *tempDict = [[NSDictionary alloc] initWithObjectsAndKeys: [objectsArray objectAtIndex: offset], #"eventStartTime", [objectsArray objectAtIndex: offset+1], #"eventEndTime", ..., [objectsArray objectAtIndex: offset+11, #"lastObject",nil];
[eventArray addObject:tempDict];
}
Then you can access each of the above objects using a similar statement as shown below:
PHSingleEvent *eventStartTime = [[eventArray objectAtIndex: index] objectForKey: #"eventStartTime"];
Hope this helps
This method will return an array of smaller arrays based on the group size you specify.
- (NSMutableArray*)makeGroupsOf:(int)groupSize fromArray:(NSArray*)array
{
if (!array || array.count == 0 || groupSize == 0)
{
return nil;
}
NSMutableArray *bigGroup = [[NSMutableArray alloc] init];
for (int i = 0; i < array.count; )
{
NSMutableArray *smallGroup = [[NSMutableArray alloc] initWithCapacity:groupSize];
for (int j = 0; j < groupSize && i < array.count; j++)
{
[smallGroup addObject:[array objectAtIndex:i]];
i++;
}
[bigGroup addObject:smallGroup];
}
return bigGroup;
}
I haven't tested it or anything though. After you have the big array with the smaller array(s) it is just a matter of filling each cell with any desired number of objects from the sub arrays.
Note: You might want to handle the cases when the array is empty, null or the group size is 0 differently.

iphone : How to make an array with objects from other arrays

I have three NSMutabelArrays, each contain about ten strings, for example:
1stArray = [NSMutableArray arrayWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",nil];
2ndArray = [NSMutableArray arrayWithObjects:#"j",#"k",#"l",#"m",#"n",#"o",#"p",nil];
3rdArray = [NSMutableArray arrayWithObjects:#"q",#"r",#"s",#"t",#"u",#"v",#"w",nil];
Now I want to make a 4th NSMutabelArrays with first 2 objects of those 3 NSMutableArray.
for example I want a 4th array like this:
4thArray = [#"a",#"b",#"j",#"k",#"q",#"r"]
How to achieve this?
I think you are looking for a code like this
int numElements = 2;
int numArrays = 3;
NSMutableArray * 4thArray = [NSMutableArray array];
for (int arrays = 0; arrays < numArrays; arrays++) {
for (int count = 0; count < numElements; count++) {
switch (arrays) {
case 0:
[4thArray addObject:[1stArray objectAtIndex:count]];
break;
case 1:
[4thArray addObject:[2ndArray objectAtIndex:count]];
break;
case 2:
[4thArray addObject:[3rdArray objectAtIndex:count]];
break;
}
}
}
Seems like this would be better solved using an array of arrays, or possibly a combination of arrays and dictionaries, depending on what you're trying to achieve. The answer to your question is trivial, so I'll point you to the NSArray Reference for that, but you probably want to consider a different approach.
do like this
NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",nil];
NSMutableArray *secArray = [NSMutableArray arrayWithObjects:#"j",#"k",#"l",#"m",#"n",#"o",#"p",nil];
NSMutableArray *thrdArray = [NSMutableArray arrayWithObjects:#"q",#"r",#"s",#"t",#"u",#"v",#"w",nil];
NSMutableArray *fourthArr = [[NSMutableArray alloc] initWithObjects:[firstArray objectAtIndex:0],[firstArray objectAtIndex:1], [secArray objectAtIndex:0],[secArray objectAtIndex:1], [thrdArray objectAtIndex:0],[thrdArray objectAtIndex:1],nil];
NSLog(#"%d", fourthArr.count);

Use a for loop to set values in an array

I have a UITableViewController that uses an array with values for every entry in the rows.
I want to set the values of that array by iterating over values read from a JSON file.
This is the new method I have created to read that data into an array and return it to my view controller. I don't know where to return the array, or how to really set it.
+(NSArray *)setDataToJson{
NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:#"Test.json"];
NSArray *test = [infomation valueForKey:#"Animals"];
for (int i = 0; i < test.count; i++) {
NSDictionary *info = [test objectAtIndex:i];
NSArray *array = [[NSArray alloc]initWithObjects:[Animal animalObj:[info valueForKey:#"AnimalName"]
location:[info valueForKey:#"ScientificName"] description:[info valueForKey:#"FirstDesc"] image:[UIImage imageNamed:#"cat.png"]], nil];
return array;
I know that my animalObj function worked when the data was local strings(#"Cat") and my dictionaryWithContentsOfJSONString works because I have tested, but I haven't used this function to set data to an array, only to UILabels, so this is where I am confused, on how to set this data into an array. But still use the For loop.
You want to use an instance of
NSMutableArray,
which will let you incrementally add elements to the array as you
iterate with the for-loop:
...
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < test.count; i++) {
NSDictionary *info = [test objectAtIndex:i];
Animal *animal = [Animal animalObj:[info valueForKey:#"AnimalName"]
location:[info valueForKey:#"ScientificName"]
description:[info valueForKey:#"FirstDesc"]
image:[UIImage imageNamed:#"cat.png"]];
[array addObject:animal];
}
return array;
Because NSMutableArray is a subclass of NSArray, there's no need change the return type of your method.

Resources