How to check the last array element and change the button image - iphone

How to get check change the button image if it reach the last element of the array and perform to start from first on click that button?
Here my code,Please help me
-(IBAction)changenext:(id)sender
{
static int j = 0;
backimg.enabled=TRUE;
if(sender == nextimg)
j++;
else if(sender == backimg)
j--;
if (j >= arcount)
{
j = 0;
}
else if(j < 0)
{
j = arcount - 1;
}
imager.image=[arimage objectAtIndex:j];
}
What change should i made?

Hi i can not clearly understand what you asking but simply you get last element of NSArray with this code :-
[myArray lastObject]
For Example:-
NSString *str = [myArray lastObject]

Related

Remove duplicates from NSArray of Custom Objects also compare and edit same

I have two NSMutableArrays. Each contains a custom word object in it. Custom word has 2 properties text and frequency. Now I want to combine these two arrays in such a way that, if these two arrays has same text in it, then it should compare the frequency of those two text and select the highest frequency of the two. And also it should remove the duplicates from the array.
I tried every logic for this but was not able to do this. Can any body help me with the logic for this. Following the code. But it should also remove the duplicates.
for (int i = 0; i < [array count]; i++) {
for (int j = 0; j < [array count]; j++) {
if ([[[array objectAtIndex:i]firstWord] isEqualToString:[[array objectAtIndex:j] firstWord]]) {
if ([[array objectAtIndex:i] frequency] < [[array objectAtIndex:j] frequency]) {
CustomWordFrequency *word = [array objectAtIndex:i];
word.frequency = [[array objectAtIndex:j] frequency];
[array replaceObjectAtIndex:i withObject:word];
}
}
}
}
Combine the two arrays.
Sort the resulting array by text ASC, frequency DESC
Loop through the array
a. Look at the next item in the array. If the text is the same as the current word, remove it from the array. If it's different, continue looping.
NSArray *combined = [firstArray arrayByAddingObjectsFromArray:secondArray];
[combined sortUsingComparator:^(id firstObject, id secondObject) {
NSComparisonResult *result = [firstObject.text compare:secondObject.text];
if (result == NSOrderedAscending) return NSOrderedAscending;
if (result == NSOrderedDescending) return NSOrderedDescending;
if (result == NSOrderedSame) {
result = [firstObject.frequency compare:secondObject.frequency];
if (result == NSOrderedAscending) return NSOrderedDescending;
if (result == NSOrderedDescending) return NSOrderedAscending;
if (result == NSOrderedSame) return NSOrderedSame;
}
}];
for (int i = 0; i < [combined count] - 2; ++i) {
CustomWordFrequency *word = [combined objectAtIndex:i];
int j = i + 1;
while ([word.text compare:[combined objectAtIndex:j].text == NSOrderedSame) {
[combined removeObjectAtIndex:j];
j++;
if (j == [combined count]) {break;}
}
if (i >= [combined count] - 2) {break;} // the count keeps changing so check here
}
NSMutableArray *combinedArray = [[NSMutableArray alloc] init];
BOOL flagForMatchFound = FALSE;
for(CustomWordFrequency *firstWord in firstArray)
{
flagForMatchFound = FALSE;
for(CustomWordFrequency *secondWord in secondArray)
{
if([firstWord.firstWord isEqualToString:secondWord.firstWord])
{
if(firstWord.frequency >= secondWord.frequency)
{
[combinedArray addObject:firstWord];
flagForMatchFound = TRUE;
}
else
[combinedArray addObject:secondWord];
}
else
{
if(!flagForMatchFound)
[combinedArray addObject:secondWord];
}
}
}

Random number generation from an NSMutable array [duplicate]

This question already has answers here:
Non repeating random numbers in Objective-C
(6 answers)
Generating non-repeating random numbers
(5 answers)
Closed 9 years ago.
I need to generate random numbers from an array i have tried this inside the for loop
rnd = arc4random_uniform(arr.count);
it generated random numbers but some numbers get repeated also tried Random() in math.h
still the same problem persists please help me out..
Thanks in advance..
if i understood
"I need to generate random numbers from an array"
correctly, you want the numbers to be taken from an array randomly, if so then
first store the numbers in an NSMutableArray
NSMutableArray *arr=//store your numbers in this array.
-(void)getRandomNumberFromArray:(NSMutableArray *)arr{
int r = arc4random() % arr.count;
int number=[arr objectAtIndex:r];
[arr removeObjectAtIndex:r];
}
Generate a random number for each element, and then check to make sure it's not the same as one of the existing ones. If it already exists, try again.
for(int i = 0; i < arr.count;i++)
{
BOOL isRandom = YES;
int rand = -1;
while(!isRandom )
(
isRandom = YES;
rand = arc4random() % 5;
for(int j = 0; j < i; j++)
{
int existingNumber = arr[j];
if(existingNumber == rand)
{
isRandom = NO;
break;
}
}
}
arr[i] = rand;
}
Another option is to first just assign them to have incrementing values, and then shuffle the mutable array. What's the Best Way to Shuffle an NSMutableArray?
If I understood your problem , then you dont need random numbers , you need to shuffle the elements in the Array ?
Then you need to use this method ,
-(void)shuffleWithArray:(NSArray*)cardsArray
{
NSMutableArray *shuffleArray =[[NSMutableArray alloc]initWithArray:cardsArray];
// NSUInteger count1=[shuffleArray count];
for (NSUInteger i= 0; i<[shuffleArray count]; i++)
{
int nElement=[shuffleArray count] -i;
int n=(arc4random()%nElement + i);
[shuffleArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
You can make use of the following function.
#property (nonatomic,strong) NSMutableArray * numbers;
- (NSInteger) nonRepeatedNumber
{
if(_numbers == nil)
{
_numbers = [[NSMutableArray alloc]init];
}
NSInteger number = arc4random()% arr.count;
while ([_numbers containsObject:[NSNumber numberWithInt:number]])
{
number = arc4random()% arr.count;;
}
[_numbers addObject:[NSNumber numberWithInt:number]];
return number;
}
Check the below Tutorial. it must help for you.
iOS Random Number generator
Try the following method
-(NSMutableArray*)randomNumbersfromArray:(NSArray*)array {
NSArray *numbers = array;
int count = [numbers count];
NSMutableArray *addedIndexes = [[NSMutableArray alloc]initWithCapacity:count];
NSMutableArray *addedObjects = [[NSMutableArray alloc]initWithCapacity:count];
int i = 0;
while ([addedIndexes count] != [numbers count]) {
int random = arc4random() % count ;
if (![addedIndexes containsObject:[NSString stringWithFormat:#"%i",random]]) {
[addedIndexes addObject:[NSString stringWithFormat:#"%i",random]];
[addedObjects addObject:[numbers objectAtIndex:random]];
i++;
}
}
return addedObjects;
}
#include <stdlib.h>
int r = 0;
if (arc4random_uniform != NULL)
r = arc4random_uniform (arr.count);
else
r = (arc4random() % arr.count);
int randomNumberFromArray=[arr objectAtIndex:r];
EDIT
Bingo.After some thinking i made it working
-(NSArray *)randomizeArray:(NSArray *)inputArray
{
NSMutableArray *checkArray=[[NSMutableArray alloc]initWithCapacity:3];
NSMutableArray *outputArray=[[NSMutableArray alloc]initWithCapacity:3];
while ([outputArray count]<[inputArray count])
{
int r=[self getRandomNumber:[inputArray count]];
if ([checkArray containsObject:[NSNumber numberWithInt:r]])
{
}
else
{
[checkArray addObject:[NSNumber numberWithInt:r]];
[outputArray addObject:[inputArray objectAtIndex:r]];
}
}
return outputArray;
}
-(int)getRandomNumber:(int)maxValue
{
int r = 0;
if (arc4random_uniform != NULL)
r = arc4random_uniform (maxValue);
else
r = (arc4random() % maxValue);
return r;
}
This randomizeArray: method will give you the whole array randomized

How to view previous array value on click

Here i used this code to view the next value in the array,
-(IBAction)changenext
{
static int j = 0;
if (j >arcount)
{
j = 0;
}
lb1.text=[NSString stringWithFormat:[artext objectAtIndex:j]];
imager.image=[arimage objectAtIndex:j];
aplayer=[[AVAudioPlayer alloc]initWithData:[arsound objectAtIndex:j] error:nil];
j++;
}
How to view the previous array value by other button click?Please help me to solve..
-(IBAction)change_next_or_prev:(id)sender
{
static int j = 0;
if(sender == btnNext)
j++;
else if(sender == btnPrev)
j--;
if (j >= arcount)
{
j = 0;
}
else if(j < 0)
{
j = arcount - 1;
}
lb1.text=[NSString stringWithFormat:[artext objectAtIndex:j]];
imager.image=[arimage objectAtIndex:j];
aplayer=[[AVAudioPlayer alloc]initWithData:[arsound objectAtIndex:j] error:nil];
}
link both button to the same action.
-(IBAction)changeprev
{
static int j = arcount;
if (j < 0)
{
j = arcount;
}
lb1.text=[NSString stringWithFormat:[artext objectAtIndex:j]];
imager.image=[arimage objectAtIndex:j];
aplayer=[[AVAudioPlayer alloc]initWithData:[arsound objectAtIndex:j] error:nil];
j--;
}

How to position the untitled section in a UITableView

At present if the sortdescriptor is having nil or empty values is being placed in an untitled section which is being placed at the top of the table. I want it to be at the end of the table. Any suggestions?
yes, it is so easy, jst perform a segmentation in which start by the charecter A and check upto z, (or whatever your requiremtn) if it matches nothing, then add it to last array that you are going to show in untititled objects. i have this for contacts. see if it is understandable by u
int numContacts=[cList count];
//NSMutableArray *nonAlphaArray=[[NSMutableArray alloc] init];
NSMutableArray *arrayCollection[27];
for (int i=0; i<27; i++) {
arrayCollection[i]=[NSMutableArray array];
}
for (int i=0; i<numContacts; i++)
{
Contact *contact= [cList objectAtIndex:i];
unichar alphaSmall='a';
unichar alphaBig='A';
unichar first=0x0000;
if([contact.mContactName length]>0)
first= [contact.mContactName characterAtIndex:0];
for (int j=0; j<26; )
{
if (first==alphaSmall || first==alphaBig)
{
[arrayCollection[j] addObject:contact];
break;
}
alphaSmall++;
alphaBig++;
j++;
if (j==26) {
[arrayCollection[26] addObject:contact];
}
}
}
for (int i=0; i<27; i++)
{
[alphaDictionary setObject:arrayCollection[i] forKey:[NSString stringWithFormat:#"%d",i]];
}

How to get index in an NSArray?

NSMutableArray*array = [[NSMutableArray alloc]init];
NSArray*Somearray = [NSArray arrayWithObjects:1st Object,2ndObject,3rd Object,4th object,5th Object,nil];
In the above array 1st Object,2ndObject,3rd Object,4th object,5th Object having val,content,conclusion in each index.
for(int i=0;i<[Somearray count];i++)
{
______________
Here the code is there to give each index ,that is having val,content,conclusion ..
After that val,content,conclusion in each index will be add to Dict..
____________
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:val,#"val",content,#"content",conclusion,#"conclusion",nil];
//Each time adding dictionary into array;
[array addObject:Dict];
}
The above Dictionary is in for loop and the keyvalue pairs will be add 5 times(Somearray Count).Now array is having in
array = [{val="1.1 this is first one",content="This is the content of 0th index",conclusion="this is the conclusion of 0th index"},{val="1.2 this is first one",content="This is the content of 1st index",conclusion="this is the conclusion of 1st index"},____,____,______,{val="1.5 this is first one",content="This is the content of 4th index",conclusion="this is the conclusion of 4th index"},nil];
Now i am having NSString*string = #"1.5";
Now i need the index where val is having 1.5 in it.How to send the str in to array to find the the index.
Can anyone share the code please.
Thanks in advance.
Use method indexOfObject
int inx= [array indexOfObject:#"1.5"];
For Find index particular key value.
int inx;
for (int i=0; i<[array count]; i++) {
if ([[[array objectAtIndex:i] allKeys] containsObject:#"val"]) {
inx=i;
break;
}
}
The method you are looking for is -[NSArray indexOfObjectPassingTest:]. You would use it like this:
NSUInteger i = [array indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return [[id objectForKey:#"val"] rangeOfString:#"1.5"].location != NSNotFound;
}];
If you just want to check that val starts with "1.5" you would use hasPrefix: instead.
Try this -
NSArray *valArray = [array valueForKey:#"val"];
int index = [valArray indexOfObject:#"1.5"];
Appended answer given by Mandeep, to show you the magic of key value coding ;)
NSUInteger idx = UINT_MAX;
NSCharacterSet* spaceSet = [NSCharacterSet whitespaceCharacterSet];
for(int i=0,i_l=[Yourarray count];i<i_l;i++) {
NSString* s_prime = [[Yourarray objectAtIndex:i] valueForKey:#"val"];
if ([s_prime length] < 4) {
continue;
}
NSString *subString = [[s_prime substringToIndex:4] stringByTrimmingCharactersInSet:spaceSet];
// NSLog(#"index %#",s);
if ([subString isEqualToString:secretNumber]){
idx = i;
break;
}
}
if (idx != UINT_MAX) {
// NSLog(#"Found at index: %d",idx);
} else {
// NSLog(#"Not found");
}