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];
Related
Given: 2 dimensional array :
[[1 2 3]
[4 5 6]
[9 8 9 ]]
Need to add diagonal of the array : 1+5+9 = 15
NSMutableArray *array = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:#1,#2,#3,nil],
[NSMutableArray arrayWithObjects:#4,#5,#6,nil],
[NSMutableArray arrayWithObjects:#9,#8,#9,nil],nil];
NSNumber* total = 0;
for (NSNumber* row in array) {
total = total + array[row][row];
}
NSLog(#"%#",total);
Here I can't access the element of the array. It gives error on "array[row][row]". What is the best way to initialize a 2D array and access the element of the array in Objective-C?
In your code, what you are doing here: for (NSNumber* row in array) is putting each element of array, inside the row variable (this is called array enumeration btw).
What you need is to use the index of the array - not the value of each element (that's what you are doing above).
Also, you don't have to use an object (NSNumber *) for your calculations. A simple NSInteger will do.
Here's the code:
NSMutableArray *array = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:#1,#2,#3,nil],
[NSMutableArray arrayWithObjects:#4,#5,#6,nil],
[NSMutableArray arrayWithObjects:#9,#8,#9,nil],nil];
NSInteger total = 0;
for (NSUInteger row = 0; row < array.count; row ++) {
total = total + [array[row][row] integerValue]; // integerValue converts the NSNumber to an NSInteger
}
NSLog(#"%d",total);
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!
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]];
}
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 would I take an array with long list of numbers that contains duplicates, so for instance:
NSArray *array = [NSArray arrayWithObjects:#"45", #"60", #"100",#"100", #"100", #"60"nil];
Just imagine that this is a HUGE list of random numbers. Now I'm sure that I have to use something like NSSet for this, but i'm not sure how to execute this. Also, once we identify the duplicates I'm guessing that I would then add those numbers to an array, and then call
[array count];
Any ideas?
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:array];
int duplicates = 0;
for (id object in set) {
if ([set countForObject:object] > 1) {
duplicates++;
}
}
This will calculate how many elements have a duplicate.
A sidenote, that array contains a bunch of strings, no numbers...
Anyway, if the goal is to get just the count you could use the following single line to get it.
NSUInteger diff = [array count] - [[array valueForKeyPath:#"#distinctUnionOfObjects.self"] count];
This uses KVC (Key-Value Coding) to get all distinct objects (that is ones without a dupe) counts them and gets the difference from the original count.
NSCountedSet is perfect for what you want to do.
NSArray *array = [NSArray arrayWithObjects:#"45", #"60", #"100",#"100", #"100", #"60",nil];
NSCountedSet *countedSet = [NSCountedSet setWithArray:array];
__block NSUInteger totalNumberOfDuplicates = 0;
[countedSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
NSUInteger duplicateCountForObject = [countedSet countForObject:obj];
if (duplicateCountForObject > 1)
totalNumberOfDuplicates += duplicateCountForObject;
NSLog(#"%# appears %ld times", obj, duplicateCountForObject);
}];
NSLog(#"Total number of duplicates is %ld", totalNumberOfDuplicates);
produces:
45 appears 1 times
60 appears 2 times
100 appears 3 times
Total number of duplicates is 5
Use filteredArrayUsingPredicate this use a predicate with your condition and return an array with the objects you need.
NSArray* arr=[[NSArray alloc] initWithObjects:#"10",#"11",#"10",#"2", nil];
NSLog(#"%d",[[arr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF == '2'"]] count]);