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

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);

Related

Matching Mutable Array value to index of another Array and getting other Array value at that index

Objective: compare values stored in Mutable array(which are changing constantly) to the index of a static Array. When the values match I would like to add the object(s) of the static array to a new mutable array.
Example:
Values of MutableArray at present state:
(1,2,3)
(Index) - Values of Static Array:
(0) - "Zero"
(1) - "One"
(2) - "Two"
(3) - "Three"
(4) - "Four"
Take values from initial MutableArray and compare them to the static array index's. Output the values at those index's to a new MutableArray
("One","Two","Three")
The initial array is derived by passing the MutableArrayContents for a search via predicate into this:
NSMutableArray *indexArray = [NSMutableArray array];
for (NSMutableArray* obj in _searchResults)
{
if([_questionsArray containsObject:obj] && ![indexArray containsObject:obj])
[indexArray addObject:#([_questionsArray indexOfObject:obj])];
}
IndexArray is the array of "index's".
I've tried for loops but they are not working correctly, any help would be appreciated.
Thanks!
You can try this:
NSArray *staticArr = #[#"Zero",#"One",#"Two",#"Three",#"Four"];
NSArray *otherArr = #[#1,#2,#3];
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:[otherArr count]];
for(int i = 0; i < [staticArr count]; i++) {
for(int j = 0; j < [otherArr count]; j++) {
if([[otherArr objectAtIndex:j] intValue] == i) {
[array insertObject:[staticArr objectAtIndex:i] atIndex:j];
break;
}
}
}
Try this method
NSArray *staticArr = #[#"Zero", #"One", #"Two", #"Three", #"Four"];
NSArray *otherArr = #[#(1), #(2), #(3)];
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[otherArr count]];
[staticArr enumerateObjectsUsingBlock:^(NSString *string, NSUInteger staticIndex, BOOL *staticStop) {
[otherArr enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger index, BOOL *stop) {
if (number.integerValue == staticIndex) {
[array insertObject:string atIndex:index];
}
}];
}];
I am typing this on a tab. Please forgive any formatting issues
NSMutableArray *indices; //I am omitting the adding of data, it contains required indices as NSNumber objects
NSArray *staticArr = #[#"One", #"Two", #"Three", #"Four", #"Five"];
NSMutableArray *array = [NSMutableArray new];
for(NSNumber *index in indices) {
NSInteger idx = [index integerValue];
If(idx < staticArr.count)
{
[array addObject:[staticArr objectAtIndex:idx];
}
}
This will be in the order of the elements in indices array and may have repetitions in case there are repetitions in indices array.
This is the most straightforward way, there are many ways to get the subarray using Apple's API

Looping thru NSArray of NSString logic

I need help with the following:
I have an NSArray with NSStrings, I want to loop thru these strings and find a matching string, when match is found the strings after this match will be extracted into an NSDictionary until a certain other match is hit.
Here is an example:
NSArray *array = #[#"Fruit",#"Apple",#"Vegtable",#"Tomato",#"Fruit",#"Banana",#"Vegtable",#"Cucumber"];
So I want to loop thru this array and split it in 2 arrays one for fruit and one for vegetable.
Anyone can help with the logic?
Thanks
This is probably the simplest way to solve the problem:
NSArray *array = #[#"Chair",#"Fruit",#"Apple",#"Orange",#"Vegetable",#"Tomato",#"Fruit",#"Banana",#"Vegetable",#"Cucumber"];
NSMutableArray *fruitArray = [NSMutableArray array];
NSMutableArray *vegetableArray = [NSMutableArray array];
NSMutableArray *currentTarget = nil;
for (NSString *item in array)
{
if ([item isEqualToString: #"Fruit"])
{
currentTarget = fruitArray;
}
else if ([item isEqualToString: #"Vegetable"])
{
currentTarget = vegetableArray;
}
else
{
[currentTarget addObject: item];
}
}
In one iteration over the array, you just keep adding items to a result array using a pointer to one of two result arrays according to the last occurrence of the #"Fruit" or #"Vegetable" string.
This algorithm ignores all items before the first occurrence of the #"Fruit" or #"Vegetable" string, because the currentTarget is initialized to nil, which ignores the addObject: messages. If you want different behaviour, just change the initialization.
You said you wanted the results in a NSDictionary, but didn't specify what should be the key. If you want one NSDictionary with two keys, Fruit and Vegetable, and values NSArrays containing the items, just use the arrays previously created:
NSDictionary *dict = #{ #"Fruit": fruitArray, #"Vegetable": vegetableArray };
PS: You have a typo in your example, Vegtable instead of Vegetable. I corrected it in my code, so keep it in mind.
If I completely understand you:
NSArray *array = #[#"Fruit",#"Apple",#"Vegtable",#"Tomato",#"Fruit",#"Banana",#"Vegtable",#"Cucumber"];
NSMutableArray *fruits = [NSMutableArray array];
NSMutableArray *vegtables = [NSMutableArray array];
for (NSInteger i = 0; i < array.count; ++i){
if ([array[i] isEqualToString:#"Fruit"]){
++i;
[fruits addObject:array[i]];
}
else if ([array[i] isEqualToString:#"Vegtable"]){
++i;
[vegtables addObject:array[i]];
}
}

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.

How can I add elements to an NSDictionary in the following format?

I have an NSArray of names and ages. Now I am trying to create a new NSDictionary with item 0 holding the first name and first age and item 1 holding the second name and second age from the corresponding NSArray? Is that possible?
In my viewDidLoad:
NSMutableArray *Names = [[NSMutableArray alloc] init];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for(int i = 0; i < 4; i++) {
[Names addObject:[candidates objectAtIndex:i]];
[ages addObject:[studenAge objectAtIndex:i]];
}
But how can I make an NSDictionary from this by order?
Final result
I want to write this NSDictionary into a .plist so it look like this:
Details
{
item 0
{
name:rahul
age:25
}
item 1
{
name:ram
age:26
}
item 2
{
name:aajy
age:20
}
item 4
{
name:raj
age:25
}
}
Dictionaries do not have an order.
Probably you want to add dictionaries to the array:
NSMutableArray *persons=[[NSMutableArray alloc]init];
for(int i=0;i<4;i++)
{
[persons addObject:# { #"name" : candidate[i], #"age" : studenAge[i] }];
}
You can sort this array with the sort-Methods of NSArray, NSMutableArray.
As mentioned by #Amin, dictionaries don't maintain order and since you seem to want an indexed access here is what I suggest as the final structure: an array of dictionaries:
NSMutableArray *details = [NSMutableArray array];
for (int i=0; i<4; i++) {
[details addObject:#{#"name": canditate[i], #"age":studentAge[i]}];
}
This will give you the following structure:
[{name:rahul, age:25}, {name:ram age:26},...]

Resources