How do you split an array of objects into an array of array of objects?
say I want to split into groups of 4, how do I do that?
[a,b,c,d,e,f,g,h] =>
[a,b] [c,d] [e,f] [g,h]
or maybe if I specify that I want to split into groups of 3, then the result should be
[a,b,c], [d,e,f], [g,h]
it should also work if h doesn't exist.
Try this logic.....
NSArray *arr = [[NSArray alloc]initWithObjects:#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",nil];
NSMutableArray *arrNew = [[NSMutableArray alloc]init];
int numberofSubArrs = 3; // change this to check the logic
for (int i=0; i<numberofSubArrs; i++) {
NSMutableArray *arrrr = [[NSMutableArray alloc]init];
[arrNew addObject:arrrr];
}
int m = 0;
for (int k=0; k<[arr count]; k++) {
[[arrNew objectAtIndex:m]addObject:[arr objectAtIndex:k]];
m++;
if (m == numberofSubArrs) {
m=0;
}
}
int g=0;
int p=0;
while(p<[arr count]) {
for (int z=0; z<[[arrNew objectAtIndex:g] count]; z++) {
[[arrNew objectAtIndex:g] replaceObjectAtIndex:z withObject:[arr objectAtIndex:p++]];
}
g++;
}
NSLog(#"Required Array is:%#",[arrNew description]);
Try this as a starting point:
NSArray *array = [NSArray arrayWithObjects:#"a", #"b", #"c", #"d", #"e", #"f", #"g", #"h", nil];
NSMutableArray *manyArrays = [NSMutableArray array];
int numberOfElementsInSubArrays = 2;
int numberOfSubArrays = ceil((float)[array count] / (float)numberOfElementsInSubArrays);
for (int i = 0; i < numberOfSubArrays; i++) {
NSMutableArray *subArray = [NSMutableArray array];
for (int j = 0; j < numberOfElementsInSubArrays; j++) {
if (i*numberOfElementsInSubArrays+j < [array count]) {
NSLog(#"Array: %d Value:%#", i, [array objectAtIndex:i*numberOfElementsInSubArrays+j]);
[subArray addObject:[array objectAtIndex:i*numberOfElementsInSubArrays+j]];
}
}
[manyArrays addObject:subArray];
}
Give this a try.
NSMutableArray *splitted = [NSMutableArray array];
id firstItem, secondItem;
for (NSInteger i=0; i <= [originalArray count]-1; i+=2) {
#try {
firstItem = [originalArray objectAtIndex:i];
secondItem = [originalArray objectAtIndex:i+1];
}
#catch (NSException *exception) {
secondItem = [NSNull null];
}
#finally {
[splitted addObject:#[firstItem,secondItem]];
}
}
Related
I have declared array in SomeClass.h It's a global variable isn't it?
#property (nonnull, nonatomic, retain) NSMutableArray *additional_tabs;
Below I declared 2 function where I use this array.
- (id _Nullable)initFromJSON:(NSDictionary *_Nullable)dictionary;
- (void)moreTabs:(NSMutableArray *_Nullable)a;
Below is if-statement I used inside initFromJSON function.
if ([Tools isNonullValueForKey:[dictionary valueForKey:#"additional_tabs"]]) {
_additional_tabs = [NSMutableArray new]; //really I need them?
_additional_tabs = [dictionary valueForKey:#"additional_tabs"];
NSLog(#"additionalTabCount (initJSON) = %lu", [_additional_tabs count]);
for (int i = 0; i < [_additional_tabs count]; i++) {
if ([Tools isNonullValueForKey:[_additional_tabs valueForKey:#"_id"]]) {
_additional_tab_id = [[_additional_tabs valueForKey:#"_id"] objectAtIndex:i];
}
if ([Tools isNonullValueForKey:[_additional_tabs valueForKey:#"names"]]) {
NSDictionary *dic = [[_additional_tabs valueForKey:#"names"] objectAtIndex:i];
_en_additional_tab_name = [dic valueForKey:#"en"];
_pl_additional_tab_name = [dic valueForKey:#"pl"];
}
if ([Tools isNonullValueForKey:[_additional_tabs valueForKey:#"url"]]) {
_additional_tab_url = [[_additional_tabs valueForKey:#"url"] objectAtIndex:i];
}
NSLog(#"%# %d %# %# %# %#", #"pos", i, #"id: ", _additional_tab_id, #"url: ", _additional_tab_url);
}
}
And this [_additional_tabs count] have 17.
But in function moreTabs:
NSLog(#"additional tabs count: %lu",[_additional_tabs count]);
for (int i = 1; i < [_additional_tabs count]; i++) {
[a addObject:[[VCTab alloc] initWithIdAndTypeAndUrl:[[_additional_tabs valueForKey:#"_id"] objectAtIndex:i] :VCTabAdditional :[[_additional_tabs valueForKey:#"url"] objectAtIndex:i]]];
}
}
return [_additional_tabs count] with nil... look like is different array or cleared?
I would be very grateful for your help :)
All the best
I am sorting an array.
There are three types of elements in the array.
1. featured
2. organic and
3. claimed.
Among them, I want to sort only organic elements and keep the featured and claimed elements at their own index.
Below is my code in which, I am extracting the claimed and featured indices in a dictionary as key being the index and value is the array element.
//Initialization
NSMutableArray *sortedArray = nil;
NSMutableDictionary *tempFeaturedDictionary = [[NSMutableDictionary alloc]init];
NSMutableDictionary *tempClaimedDictionary = [[NSMutableDictionary alloc]init];
NSMutableArray *tempOrganicArray = [[NSMutableArray alloc]init];
for (int i = 0; i < array.count; i++) {
DRListing *isFeaturedObj = (DRListing*)[array objectAtIndex:i];
if (isFeaturedObj.featured) {
[tempFeaturedDictionary setObject:isFeaturedObj forKey:[#(i)stringValue]];
}else if (isFeaturedObj.claimed)
{
[tempClaimedDictionary setObject:isFeaturedObj forKey:[#(i)stringValue]];
}else
[tempOrganicArray addObject:isFeaturedObj];
}
Again I am adding the claimed and featured back to their original indices after sorting as:
sortedArray = [NSMutableArray arrayWithArray:[tempOrganicArray sortedArrayUsingDescriptors:sortDescriptorsArray]];
for (int i = 0; i<sortedArray.count; i++) {
for (NSString *key in tempFeaturedDictionary) {
if ( [[#(i)stringValue] isEqualToString: key] ) {
[sortedArray insertObject:[tempFeaturedDictionary objectForKey:[#(i)stringValue]] atIndex:i];
}}
for (NSString *key in tempClaimedDictionary) {
if ([[#(i)stringValue]isEqualToString:key ]) {
[sortedArray insertObject:[tempClaimedDictionary objectForKey:[#(i)stringValue]] atIndex:i];
}
}
}
The code works good. Except there is claimed/(and)featured elements at the last index of the 'array'. Because the 'sortedArray' index remains less than the 'array.count' in this scenario.
Thanks in advance.
Update -
I receive response array of type:
[{featured1 featured2}, {organic1, organic2..}, {claimed1}, {featured11, featured12}, {organic11, organic12..}, {claimed2}, ..]
and I am allowed to sort only organic elements within this array. Featured and claimed should not loose their original index position.
I would iterate through the array, extracting the organics to sort. Then sort your organic array. Then iterate through the original array taking either the element from the original array or an element from the sorted organics array as appropriate.
NSMutableArray *organicsArray = [NSMutableArray new];
for (int i = 0; i < array.count; i++) {
DRListing *isFeaturedObj = (DRListing*)array[i];
if ((!isFeaturedObj.featured) && (!isFeaturedObj.claimed)) {
[organicsArray addObject:isFeaturedObj];
}
}
NSMutableArray *sortedOrganicsArray = [[organicsArray sortedArrayUsingDescriptors:sortDescriptorsArray] mutableCopy];
NSMutableArray *outputArray = [NSMutableArray new];
for (int i = 0; i < array.count; i++) {
DRListing *isFeaturedObj = (DRListing*)array[i];
if ((!isFeaturedObj.featured) && (!isFeaturedObj.claimed)) {
[outputArray addObject:sortedOrganicsArray[0]];
[sortedOrganicsArray removeObjectAtIndex:0];
} else {
[outputArray addObject:isFeaturedObject];
}
}
You could possibly make it a little more efficient if you reversed your sort order for the organics array since then you could say
[outputArray addObject:[sortedOrganicsArray lastObject]];
[sortedOrganicsArray removeLastObject];
But if your array isn't particularly large then the performance improvement will probably be negligible.
Maybe this is an alternative:
NSMutableArray *organics = [NSMutableArray new];
NSMutableArray *others = [NSMutableArray new];
for (DRListing *isFeaturedObj in array) {
if (isFeaturedObj.organic) {
[organics addObject:isFeaturedObj];
} else {
[others addObject:isFeaturedObj];
}
}
NSMutableArray *sorted = [NSMutableArray alloc]initWithObjects:organics,others, nil];
You can take the first 2 functions. The others are what I used for testing.
- (DRListing *)getNextObjectFromArray:(NSArray *)array WithStartingIndex:(int)index
{
for (int i=index; i<array.count; i++) {
DRListing *obj = (DRListing*)[array objectAtIndex:i];
if (!obj.featured && !obj.claimed)
{
return obj;
}
}
return nil;
}
- (void)sortArray:(NSMutableArray *)array
{
for (int pass = 0; pass<array.count-1; pass++) {
for (int i=0; i<array.count-1; i++) {
DRListing *obj = [self getNextObjectFromArray:array WithStartingIndex:i];
int foundIndex = (int)[array indexOfObject:obj];
DRListing *obj2 = [self getNextObjectFromArray:array WithStartingIndex:foundIndex+1];
int foundIndex2 = (int)[array indexOfObject:obj2];
if (obj!=nil && obj2 !=nil) {
if (obj.value >= obj2.value) {
[array exchangeObjectAtIndex:foundIndex withObjectAtIndex:foundIndex2];
}
i = foundIndex;
}
}
}
NSLog(#"Sorted Data: %#",array);
}
- (NSMutableArray *)testData
{
NSMutableArray *array = [NSMutableArray new];
for (int i=0; i<20; i++) {
DRListing *obj = [DRListing new];
obj.featured = i*i%2;
obj.claimed = i%2;
obj.value = i*3%10;
[array addObject:obj];
}
NSLog(#"Test Data: %#",array);
return array;
}
#interface DRListing : NSObject
#property (nonatomic) BOOL featured;
#property (nonatomic) BOOL claimed;
#property (nonatomic) int value;
#end
I would like to create an array for iOS platform like the PHP syntax below, many thanks ~~
$createArray = array ();
for ($i = 0; $i<10; $i++) {
$createArray[$i]['name'] = $name;
$createArray[$i]['age'] = $age;
}
Save your values in NSDictionary and add that dictionary into your array
NSMutableArray *theArray = [NSMutableArray array];
for (int indexValue = 0; indexValue<10; indexValue++) {
NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init];
[theDictionary setObject:name forKey:#"name"];
[theDictionary setObject:age forKey:#"age"];
[theArray addObject:theDictionary]
}
While Retrieving time,
NSString *name = [[theArray objectAtIndex:indexValue] objectForKey:#"name"];
NSString *age = [[theArray objectAtIndex:indexValue] objectForKey:#"age"];
you might find it helpful:
array = [[NSMutableArray alloc] init];
for (int i = 0; i < 8; i++) {
NSMutableArray *subArray = [[NSMutableArray alloc] init];
for (int j = 0; j < 8; j++) {
[subArray addObject:[NSNumber numberWithInt:0]];
}
[array addObject:subArray];
[subArray release];
}
also check this question
Try this.
array = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
NSMutableArray *subArray = [[NSMutableArray alloc] init];
for (int j = 0; j < 2; j++) {
//Do your Stuff
// [subArray addObject:name];
// [subArray addObject:Age];
}
[array addObject:subArray];
}
OR
Why can't try with the NSDictionary
You can use this. But this is not better way in IOS.
NSMutableArray *array[20];
for (int i=0;i< 20; i++)
{
array[i] = [NSMutableArray array];
for (int j=0;j<3;j++)
{
NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init];
[theDictionary setObject:name forKey:#"name"];
[theDictionary setObject:age forKey:#"age"];
[[array[i] addObject:theDictionary]
}
}
First you to have set An NSMutableDictionary on .h file
#interface MSRCommonLogic : NSObject
{
NSMutableDictionary *twoDimensionArray;
}
then have to use following functions in .m file
- (void)setValuesToArray :(int)rows cols:(int) col value:(id)value
{
if(!twoDimensionArray)
{
twoDimensionArray =[[NSMutableDictionary alloc]init];
}
NSString *strKey=[NSString stringWithFormat:#"%dVs%d",rows,col];
[twoDimensionArray setObject:value forKey:strKey];
}
- (id)getValueFromArray :(int)rows cols:(int) col
{
NSString *strKey=[NSString stringWithFormat:#"%dVs%d",rows,col];
return [twoDimensionArray valueForKey:strKey];
}
I am trying this code for generating a random number and saving the list of numbers in an array, then i am trying to delete those numbers from the list one by one which appeared once, e.g
1, 5, 9 , 4, 3, 7 ,6 ,10, 11, 8, 2 are the list of integers now 9 is appeared once and now i do not need 9 again.. this is my code of random non repeating numbers array.
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
BOOL record = NO;
int x;
for (int i=0; [storeArray count] < 10; i++) //Loop for generate different random values
{
x = arc4random() % 10;//generating random number
if(i==0)//for first time
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
else
{
for (int j=0; j<= [storeArray count]-1; j++)
{
if (x ==[[storeArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
{
record = NO;
}
else
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
}
}
Try this,
NSArray *arrRandoms = [[NSArray alloc]initWithObjects:1,5,8,7,36,17,96,32,5,7,8,13,36,nil] ; // This contains your random numbers
NSMutableArray *arrFresh = [[NSMutableArray alloc]init];
// Now removing the duplicate numbers
BOOL checkRepeat = NO;
int _Current;
for (int i=0; i<[arrRandoms count]; i++)
{
_Current = [arrRandoms objectAtIndex:i];
if (i == 0)
[arrFresh addObjects:_Current];
else
{
checkRepeat = NO;
for(int j=0; j< [arrFresh count]; j++)
{
if ( _Current == [arrFresh objectAtIndex:j])
checkRepeat = YES;
}
if (checkRepeat == NO)
[arrFresh addObjects:_Current];
}
}
I think this code will work. Check It.
try it
//**************remove repeat objects from array***************************//
NSArray *noDuplicates = [[NSSet setWithArray: yourArray] allObjects];
you add
.h file
BOOL isSame;
NSMutableArray *countArray;
NSInteger randomNumber;
.m file
countArray=[[NSMutableArray alloc]init];
//get randon no
-(NSInteger)getRandomNo:(NSInteger)range
{
isSame=TRUE;
while (isSame){
isSame = FALSE;
randomNumber = arc4random() % range;
for (NSNumber *number in countArray){
if([number intValue] ==randomNumber){
isSame = TRUE;
break;
}
}
}
[countArray addObject:[NSNumber numberWithInt:randomNumber]];
return randomNumber;
}
Tested Please try this,
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
NSMutableSet * setUnique = [[NSMutableSet alloc] init];
for (int i=0; [setUnique count] < 10; i++) //Loop for generate different random values
{
[setUnique addObject:[NSNumber numberWithInt:arc4random() % 10]];
}
storeArray = [[setUnique allObjects] mutableCopy];
// check this how to get random number in array (i.e.. this array(below arr_numbers) contain non repeated number)
// for general purpose i am posting this.. so people cannot check for another answer
int num_count = 10;
int RandomNumber;
NSMutableArray *arr_numbers = [[NSMutableArray alloc] init];
for (int j =0; j < num_count; j++)
{
RandomNumber = 0 + arc4random() % num_count;
NSLog(#"%d",RandomNumber);
if ([arr_numbers count]>0)
{
if (![arr_numbers containsObject:[NSNumber numberWithInt:RandomNumber]])//
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
if (j == num_count-1)
{
if ([arr_numbers count] != num_count)
{
j = 0;
}
}
}
else
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
}
NSLog(#"%#",arr_numbers);
I want to compare 2 NSMutableArray and get different object into third Array. How can i do that ?
Array1 can loop object .
Array1 = "a", "b","c","d","a","b","c";
Array2 = "a", "b", "c";
And then result
Array3 = "d";
Thanks in advance
Use sets for set operations:
NSSet *set1 = [NSSet setWithArray:array1];
NSMutableSet *set2 = [NSMutableSet setWithArray:array2];
[set2 minusSet:set1];
You Can try this too.
NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"1", nil];
NSMutableArray *array2 = [[NSMutableArray alloc]initWithObjects:#"2",#"1", nil];
NSMutableArray *largeArray;
NSMutableArray *shortArray;
if([array1 count] > [array2 count]){
largeArray = array1;
shortArray = array2;
} else {
largeArray = array2;
shortArray = array1;
}
[largeArray removeObjectsInArray:shortArray];
for (NSString *va in largeArray) {
NSLog(#"%#",va);
}
NSMutableArray *gotDiffArry= [[NSMutableArray alloc] init];
for(int i = 0 ; i < FirstArray.count; i++) {
if(i < seconArray.count){
if(![seconArray[i] isEqual:firstArray[i]]){
[gotDiffArry addObject:[NSNumber numberWithInt:i]];
}
} else {
[gotDiffArry addObject:[NSNumber numberWithInt:i]];
}
}
EDITED:
for (int i = 0 ; i < firstArray.count ; i ++)
{
NSString *search = [firstArray objectAtIndex:i];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY SELF CONTAINS %#", search];
NSMutableArray *temAraay = [secondArray filteredArrayUsingPredicate: predicate];
if(temArray.count >=0 )
{
NSLog("%#", [temArray objectAtIndex:0]);
}
}
I have used the following and got the desired results:
for(int i =0; i<[arraytwo count]; i++)
{
if (![arrayone containsObject:[arraytwo objectAtIndex:i]])
[arraythree addObject: [arraytwo obectAtIndex:i]];
}
NSLog(#"%#",arraythree);