Objective-C check if item exists in NSMutableArray - ios

I have this section of code here:
for (int i = 0; i<[taskData count]; i++)
{
for (int j=0; j<[allJobTaskArray count]; j++)
{
NSLog(#"%d", i);
NSLog(#"%d", j);
PunchListDataCell *pldCell = [[[PunchListDataCell alloc]init] autorelease];
pldCell.stringData= [self reverseStringDate:[[[allJobTaskArray objectAtIndex:j] objectAtIndex:i] substringToIndex:10]];
pldCell.cellSelected = NO;
[punchListData addObject:pldCell];
}
}
Now let me explain:
taskData count is 57 and is a NSArray
allJobTaskArray count is 12 and is a NSMutableArray
This code will crash at this line: pldCell.stringData= [self reverseStringDate:[[[allJobTaskArray objectAtIndex:j] objectAtIndex:i] substringToIndex:10]]; when j is 6 and i is 36 simple because in allJobTaskArray objectAtIndex: 6 objectAtIndex: 36 does not exist.
This is the error I am getting: [__NSCFArray objectAtIndex:]: index (36) beyond bounds (36)
What I am trying to do is if the item does not exist, then pldCell should equal #"";
My question is how would I check if I am item exist or not ?
I have tried the following:
if([[allJobTaskArray objectAtIndex:j] objectAtIndex:i] == [NSNull null]){
pldCell.stringData = #"";
}else{
pldCell.stringData= [self reverseStringDate:[[[allJobTaskArray objectAtIndex:j] objectAtIndex:i] substringToIndex:10]];
}

Altogether it should look something like -
for (int i = 0; i<[taskData count]; i++)
{
for (int j=0; j<[allJobTaskArray count]; j++)
{
NSLog(#"%d", i);
NSLog(#"%d", j);
PunchListDataCell *pldCell = [[[PunchListDataCell alloc]init] autorelease];
if ([[allJobTaskArray objectAtIndex:j] count] > i) {
pldCell.stringData= [self reverseStringDate:[[[allJobTaskArray objectAtIndex:j] objectAtIndex:i] substringToIndex:10]];
} else {
pldCell.stringData = #"";
}
pldCell.cellSelected = NO;
[punchListData addObject:pldCell];
}
}

Related

How to reference an array from another function Objective-C

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

Displaying Array in NSLog

I have made a basic card shuffling algorithm.
I want to check if its working through the nslog.
It crashes the app and puts in a break point at the nslog
Can someone help with doing so?
-(IBAction)suffle:(id)sender
{
NSMutableArray *arrayExample = [[NSMutableArray alloc] init];
[arrayExample addObject:[NSNumber numberWithInt:1]];
[arrayExample addObject:[NSNumber numberWithInt:2]];
[arrayExample addObject:[NSNumber numberWithInt:3]];
[arrayExample addObject:[NSNumber numberWithInt:4]];
for (int i = 0; i < [arrayExample count]; ++i) {
int r = (random() % [arrayExample count]);
[arrayExample exchangeObjectAtIndex:i withObjectAtIndex:r];
NSLog(#"%#", [arrayExample description]);
}
}
Here is my code
Maybe this routine help you.
- (NSMutableArray *)generateRandomNumbers:(NSNumber *)numberOfElements {
NSMutableArray *arrayRandomPositions = [[NSMutableArray alloc] init];
// First create sequential numbers array
for (int i=0; i<[numberOfElements integerValue]; i = i +1) {
[arrayRandomPositions addObject:[NSNumber numberWithInt:i]];
}
// Make the shuffle
for (int i = 0; i < [numberOfElements integerValue]; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = (int)[numberOfElements integerValue] - i;
int n = arc4random_uniform(nElements) + i;
[arrayRandomPositions exchangeObjectAtIndex:i withObjectAtIndex:n];
}
return arrayRandomPositions;
}

How to delete the number from non repeating number array?

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

words from letters

I am working in iOS, and I am facing one problem. I have 6 letters, and I want to find all strings that can be generated by these 6 letters. The sequence and length of the string doesn't matter here, also the meaning of the string doesn't matter because we can check the string with a dictionary to find if it is a valid word or not.
So is there any algorithm to find this?
For example:
Input 6 letters are : N T L P A E
Expected output will be:
plan
net
planet
lan
tea
lap
..
..
Here the words in the output are only the valid words, but the output should contain all possible words, even invalid words.
This should probably solve this:
+ (void) logPermutations:(NSArray*)objects
{
if (objects == nil || [objects count] == 0) {
return;
}
NSMutableArray* copy = [objects mutableCopy];
[self logPermutations:copy logedSoFar:#""];
}
+ (void) logPermutations:(NSMutableArray*)objects
logedSoFar:(NSString*)log
{
if (objects == nil || [objects count] == 0) {
return;
}
NSUInteger count = [objects count];
for (NSUInteger i = 0; i < count; ++i) {
id removed = [objects objectAtIndex:i];
[objects removeObjectAtIndex:i];
NSString* newlog = [NSString stringWithFormat:#"%#%#",log,[removed description]];
NSLog(#"%#",newlog);
[self logPermutations:objects logedSoFar:newlog];
[objects insertObject:removed atIndex:i];
}
}
-(NSMutableArray*)genValidWords:(NSString*)tiles
{
/*===============EMPTY PREVIOUS ARRAY=================*/
FINAL_VALID_WORDS=[[NSMutableArray alloc] init];
posWords=[[NSMutableArray alloc] init];
genWords=[[NSArray alloc] init];
/*============EMPTY PREVIOUS ARRAY FINISH=============*/
/*===============POSSIABLE NO OF WORDS FROM GIVEN LETTERS=================*/
int length=[tiles length];
int total=0;
for(long i=2;i<[tiles length]+1;i++)
total=total+([self factorialX:length]/[self factorialX:length-i]);
NSLog(#"POSSIABLE NO OF WORDS FROM LETTERS \"%#\" IS %d",tiles,total);
/*===============POSSIABLE NO OF WORDS FROM GIVEN LETTERS FINISH=================*/
/*===============GET ARRAY OF ALL POSSIABLE WORDS FROM GIVEN LETTERS=============*/
for(int i=2;i<[tiles length]+1;i++)
{
genWords=getPermutations(tiles, i);
[posWords addObjectsFromArray:genWords];
}
NSLog(#"%#",posWords);
return posWords;
}
static NSMutableArray *results;
void doPermute(NSMutableArray *input, NSMutableArray *output, NSMutableArray *used, int size, int level)
{
if (size == level)
{
NSString *word = [output componentsJoinedByString:#""];
//if(check(word))
[results addObject:word];
return;
}
level++;
for (int i = 0; i < input.count; i++)
{
if ([used[i] boolValue])
{
continue;
}
used[i] = [NSNumber numberWithBool:YES];
[output addObject:input[i]];
doPermute(input, output, used, size, level);
used[i] = [NSNumber numberWithBool:NO];
[output removeLastObject];
}
}
NSArray *getPermutations(NSString *input, int size)
{
results = [[NSMutableArray alloc] init];
NSMutableArray *chars = [[NSMutableArray alloc] init];
for (int i = 0; i < [input length]; i++)
{
NSString *ichar = [NSString stringWithFormat:#"%c", [input characterAtIndex:i]];
[chars addObject:ichar];
}
NSMutableArray *output = [[NSMutableArray alloc] init];
NSMutableArray *used = [[NSMutableArray alloc] init];
for (int i = 0; i < chars.count; i++)
{
[used addObject:[NSNumber numberWithBool:NO]];
}
doPermute(chars, output, used, size, 0);
return results;
}
-(double) factorialX: (int) num {
double tempResult = 1;
for (int i=2; i<=num; i++) {
tempResult *= i;
}
return tempResult;
}
/*=======================Call Like this====================
NSmutableArray=getPermutations("Pass your string", pass your lenght);
NsmutableArray=getPermutations("Janak", 2);
NSMutableArray=[self genValidWords:#"Hello"];
will return all possiable combination of two letters
=======================xxxxxxxxxx====================*/
I got the solution,
I want something like following.
-(NSArray*)totalWords:(NSArray*)letters
{
NSMutableArray *output=[[NSMutableArray alloc]init];
for (int i=0; i<letters.count; i++)
{
for (int j=0; j<letters.count; j++)
{
if (i==j) continue;
for (int k=0; k<letters.count; k++)
{
NSString *str=[NSString stringWithFormat:#"%#%#%#",letters[i],letters[j],letters[k]];
if(i!=j && j!=k && i!=k &&[self checkmeaning:str])
[output addObject:str];
for (int l=0; l<letters.count; l++)
{
NSString *str=[NSString stringWithFormat:#"%#%#%#%#",letters[i],letters[j],letters[k],letters[l]];
if(i!=j && j!=k && i!=k && l!=i && l!=j && l!=k &&[self checkmeaning:str])
[output addObject:str];
for (int m=0; m<letters.count; m++)
{
NSString *str=[NSString stringWithFormat:#"%#%#%#%#%#",letters[i],letters[j],letters[k],letters[l],letters[m]];
if(i!=j && j!=k && i!=k && l!=i && l!=j && l!=k && m!=i && m!=j && m!=k && m!=l &&[self checkmeaning:str])
[output addObject:str];
for (int n=0; n<letters.count; n++)
{
NSString *str=[NSString stringWithFormat:#"%#%#%#%#%#%#",letters[i],letters[j],letters[k],letters[l],letters[m],letters[n]];
if(i!=j && j!=k && i!=k && l!=i && l!=j && l!=k && m!=i && m!=j && m!=k && n!=i && n!=j && n!=k &&n!=m &&n!=l && m!=l&&[self checkmeaning:str])
[output addObject:str];
}
}
}
}
}
}
NSLog(#"count :%i",[output count]);
NSLog(#"output array :\n%#",output);
return output;
}

split array of objects into groups of 4 - ios

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]];
}
}

Resources