display images randomly in 3 UIButton using single array content - ios

I have created three UIButton and i have 11 images in an array. I want to display that images randomly in each and every buttons.
Edited
button2Image, button3Image, button4Image is NSString,
button2Image = [topButtonArray objectAtIndex:l1Counter];
NSArray *reversed = [[testArray reverseObjectEnumerator] allObjects];
button3Image = [topButtonArray objectAtIndex:nextCounter+1];
int random = arc4random_uniform([topButtonArray count]);
button4Image = [topButtonArray objectAtIndex:random];
Note: I don’t want to display same image in each button.

NSArray *urImageArray;//11 images
NSMutableArray *threeImages = [[NSMutableArray alloc]init];
while ([threeImages count]<3) {
id image=[urImageArray objectAtIndex:[self getRandomNumberBetween:0 maxNumber:11-1]];
// Three images must be different
if (![threeImages containsObject:image]) {
[threeImages addObject:image];
}
}
firstButtonImage = [threeImages objectAtIndex:0];
twoButtonImage = [threeImages objectAtIndex:1];
thirdButtonImage = [threeImages objectAtIndex:2];
- (NSInteger)getRandomNumberBetween:(NSInteger)min maxNumber:(NSInteger)max
{
return min + arc4random() % (max - min + 1);
}

If the question is how to pick random elements from array, here is a nice article with examples: http://nshipster.com/random/.
For example:
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
//i is number of required random elements
int i = 3;
while (i-->0)
{
if ([array count] > 0) {
int idx = arc4random_uniform([array count]);
[resultArray addObject:array[idx]];
//array is a mutable array whether the original one or it's deep copy
[array removeObjectAtIndex:idx];
}
}

For that you have to non-repeating random number. Then use that number to get the image from image array
arr123=[[NSMutableArray alloc]init];
int random = arc4random_uniform(11);
[arr123 addObject:[NSString stringWithFormat:#"%d",random]];
[self do1];
NSLog(#"%#",arr123);
int iMatch=0;
-(void)do1
{
int random = arc4random_uniform(11);
if([arr123 count]==2)
return;
for(int i=0;i<1;i++)
{
for(int j=0;j<[arr123 count];j++)
{
if(random==[[arr123 objectAtIndex:j] intValue])
{
iMatch=1;
break;
}
}
if(iMatch==1)
{
iMatch=0;
[self do1];
}
else
{
iMatch=0;
[arr123 addObject:[NSString stringWithFormat:#"%d",random]];
[self do1];
}
}
}
Then use the arr123 array to get the random images from image array using the random indexes

you should create an NSSet with the objects you get from the array. The NSSet has only distinct objects so you will add random objects from the array to the NSSet until the NSSet counts 3 objects. Look at apple NSSet documentation:
https://developer.apple.com/library/mac/documentation/cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html

Related

How to compare two nsarrays with different values?

Hi i have two nsarrays.
Array A:
arrProductSelection = [[NSArray alloc]initWithObjects:#"English",#"German",#"Russian",#"Chinese",#"Spanish",#"French",#"French",#"French",#"French",#"French",#"French",#"French",#"French",nil];
Array B:
arrProductSelectionB = [[NSArray alloc]initWithObjects:#"deselcted",#"selected",#"selected",#"selected",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",nil];
I need to compare two arrays and get the value from array A by comparing with array B having value as selected. That is i should get german,chinese and russian sepearted by comma as nsstring.
Try this:
NSMutableArray *arrSelected = [[NSMutableArray alloc] init];
NSArray *arrProductSelection = [[NSArray alloc]initWithObjects:#"English",#"German",#"Russian",#"Chinese",#"Spanish",#"French",#"French",#"French",#"French",#"French",#"French",#"French",#"French",nil];
NSArray *arrProductSelectionB = [[NSArray alloc]initWithObjects:#"deselcted",#"selected",#"selected",#"selected",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",nil];
for(int i = 0; i< arrProductSelectionB.count-1;i ++) {
if ([arrProductSelectionB[i] isEqualToString:#"selected"]) {
[arrSelected addObject:arrProductSelection[i]];
}
}
NSString *strSelected = [arrSelected componentsJoinedByString:#","];
NSLog(#"%#", strSelected);//output: German,Russian,Chinese
If you can make this type of array then manage easly.
(
{
flag = deselcted;
name = English;
},
{
flag = selected;
name = German;
},
{
flag = deselcted;
name = Russian;
},
{
flag = deselcted;
name = Chinese;
}
)
==> Array[(dictionary),(dictionary),.....]
if you need result in an array, Here is the function:
NSMutableArray*resultArray=[[NSMutableArray alloc]init];
for(int i=0; i<arrProductSelectionB.count;i++){
if ([[arrProductSelectionB objectAtIndex:i]isEqualToString:#"selected"]) {
[resultArray addObject:[arrProductSelection objectAtIndex:i]];
}
}
resultArrayhave the values which you need.
first i would make sure both arrays have same counters for safety something like
if (arrProductSelection.count == arrProductSelectionB) {
//than all you need is one for cycle something like :
for (int i = 0; i < arrProductionSelectionB.count; i++) {
if ([arrProductionSelectionB[i] isEqualToString: #"selected"]) {
do something magically with arrProductSelection[i];
}
}
}

How to remove value from NSMutableArray

I have a NSMutableArray "coordinates" which gives me values like this
2014-01-11 09:52:15.479 DreamCloud[397:70b] (
{
1000 = {
Linecolor = 0X6495ED;
Lines = "4-s";
Xcord = "77.000000";
Xposition = "54.500000";
Ycord = "111.500000";
Yposition = "51.500000";
};
},
{
1001 = {
Linecolor = 0X6495ED;
Lines = "4-s";
Xcord = "45.000000";
Xposition = "42.500000";
Ycord = "417.000000";
Yposition = "54.000000";
};
},
{
1000 = {
Linecolor = 0X6495ED;
Lines = "4-s";
Xcord = "73.000000";
Xposition = "50.500000";
Ycord = "111.000000";
Yposition = "51.000000";
};
}
)
Within this I need ti remove the values for 1001 and recreate the array without 1001 . How do I do this.I am new in ios so I did not figure out how to do this .
for (NSMutableDictionary *deltag in deletelinearray)
{
NSMutableDictionary *gettagsdeleted = [deltag objectForKey:[NSString stringWithFormat:#"%d",myV.tag]];
NSLog(#"%#",gettagsdeleted);
int starttag=[gettagsdeleted objectForKey:#"Starttag"];
int endtag=[gettagsdeleted objectForKey:#"Endtag"];
}
NSLog(#"%#",coordinates);
Above is the code where in "coordinates " I get the array and start-tags and end-tags are 1000, 1001 . In coordinates I don't know the index as Kumar Kl said .
Consider your array name is coorditates
for (NSDictionary *dict in coorditates) {
if ([dict objectForKey:[NSString stringWithFormat:#"%d",1001]]) {
[coorditates removeObject:dict];
break;
}
}
You can also use NSPredicate but, for that coorditates array must be NSMutableArray
NSPredicate *pred = [NSPredicate predicateWithFormat:#"ANY self.#allKeys != %#", #"1001"];
[coorditates filterUsingPredicate:pred];
Try this for loop instead. Instead of selecting the object with the key it removes it.
for (NSMutableDictionary *deltag in deletelinearray)
{
[coordinates removeObjectForKey:[NSString stringWithFormat:#"%d",myV.tag]];
}
It is not a good coding practice to modify(insert or delete) the items in array while enumerating it. So first find your index and then delete it.
You don't need to create a new array, once the details with "1001" is removed. You already have an update array.
NSString *deleteKey=#"1001";
__block int deleteIndex=-1;
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
for (NSString *key in [obj allKeys]) {
if([key isEqualToString:deleteKey]){
deleteIndex=idx;
*stop=YES;
}
}
}];
if(deleteIndex>=0){
[arr removeObjectAtIndex:deleteIndex];
}
You want to call the removeObjectAtIndex: function, but it appears your array contains dictionary objects and you want to remove the one with the key 1001. What you want to avoid is removing the object WHILE looping through the array.
So, what I would do is create a variable that will hold the index of the item once you find it, then loop through the array and once you find the object that it matches store the index and break. After, you shouldn't need to recreate the array after you remove the item, removing the object at the index you provide the above function will do just that for you. In your case, you'll want to do the following:
NSString *key = #"1001";
for (NSInteger index = 0; index < array.count; index++) {
NSDictionary *dictionary = coordinates[index];
if (dictionary[key]) {
indexToDelete = index;
break;
}
}
[coordinates removeObjectAtIndex:1001];
int i = 0;
for (NSDictionary *dict in coorditates)
{
if ([dict objectForKey:#"1001"])
{
[coorditates removeObjectAtIndex:i];
}
i++;
}

Out of the remaining numbers i wanted to choose some numbers but based on a certain counter variable whose value is randomly determined

I have an array that holds numbers from 1 to 7. Now i am selecting specific numbers and putting it on another subarray. If it doesn't contain those specific numbers i wanted to choose some numbers but based on a certain counter variable whose value is randomly determined. That is for example if counter value is 2 only two numbers from the remaining array elements must be chosed.
This might be a simple question but i need help as i am a beginner to ios and objective c
thanks in advance
what i have tried is
int counter = (arc4random()%(4-1))+1
for(int i=0; i<[mainarray count];i++)
{
if([[[mainarray objectAtIndex:i] objectAtIndex:1] integerValue]==specificnum)
{
[subarray addObject:[mainarray objectAtIndex:i]];
}
else if(counter==1)
{
[subarray addObject:[mainarray objectAtIndex:i]];
}
}
i am actually stuck in the else part
I am here showing arrays with sample values. Try this
int counter = (arc4random()%(4-1))+1;
int specificnum = 4;
NSLog(#"Counter:%i ",counter);
NSArray *mainarray = [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7", nil];
NSMutableArray *subarray = [[NSMutableArray alloc]init];
for(int i=0; i<[mainarray count];i++)
{
if([[mainarray objectAtIndex:i] integerValue]==specificnum)
{
[subarray addObject:[mainarray objectAtIndex:i]];
}
else if(counter!=0)
{
[subarray addObject:[mainarray objectAtIndex:i]];
counter--;
}
}
NSLog(#"Array: %#",subarray );
int[] mainarray;
int[] subarray;
//suppose you have moved some array elements from mainarray to subarray.
//find present array length of main array
int main_length=mainarray.length();
int subarray_length=subarray.length();
Random rand = new Random();
int counter== rand.nextInt(main_length) + 1;
for(int i=0;i<counter;i++)
{
subarray[subarray_length]=mainarray[counter];
subarray_length++
}

In Objective-C Check an array of Integer Values and see if at least ONE is > 0

I asked a similar question to test an Array of Bool values here but now I have changed it so the values are now Integer values and I want to see if any of them are positive.
Example, I add 10 new objects in a loop like below, then at some point some may change and then I need to do a test. It may be that I do not use NSNumber, as long as I cna get an int out of it.
// I create an array like
NSMutableArray *MyArray = [[NSMutableArray alloc]init];
for (int count = 0; count < 10; count++)
{
[MyArray addObject:[NSNumber numberWithInt:0]];
}
// At some point I change a value or two
[MyArray replaceObjectAtIndex:3 withObject:[NSNumber numberWithInt:5]];
....
....
....
....
[MyArray replaceObjectAtIndex:3 withObject:[NSNumber numberWithInt:7]];
if([MyArray containsPositiveObject])
{
// Get the integer
int MyValue = [MyArray[4]integerValue];
}
EDIT
I have tried this and it works but wondered if there was a faster method.
if([self containsPositiveValue:selectedItems])
{
// Do my stuff
}
And then
-(bool)containsPositiveValue:(NSArray *)numberArray
{
bool result = NO;
for (NSNumber *obj in numberArray)
{
if([obj integerValue])
{
result = YES;
break;
}
}
return result;
}
Try this.
NSArray *array = #[ #(-1) , #(-3) , #(0) , #(-4) , #(2) , #(-1) ]; // zero is not positvie or negitive
NSArray *newArray = [array filteredArrayUsingPredicate: [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return ( [evaluatedObject isKindOfClass:[NSNumber class]] && ([evaluatedObject integerValue] > 0) );
return NO;
}]];
if (newArray.count)
{
NSLog(#"There are positive values");
}
else
{
NSLog(#"There are no positive values") ;
}
Surely the simplest way would be to go:
NSArray * array = #[#(-1), #(-5), #(-5)];
for (NSNumber * number in array) {
if (number.intValue > 0) {
NSLog(#"Positive Values");
// Add custom code here
break;
}
}
This will then check if at least one item in the array is greater than zero and custom code can then be implemented.
I suppose it depends if you want to perform something if there are no positive values and something different if there is?
You could always add something like this:
NSArray * array = #[#(-1), #(-5), #(-5)];
NSInteger largestValue = 0;
for (NSNumber * number in array) {
if (number.intValue > largestValue) {
largestValue = number.intValue;
}
if (largestValue > 0) {
break;
}
}
if (largestValue > 0) {
NSLog(#"Positive Value");
}
else {
NSLog(#"All Negative Values");
}
Anyway it gets more complicated the more complicated you want it to work but it should be incredibly simple

Quiz application - How can I choose 3 wrong answers to show from an array of 6 wrong answers?

I am trying to make a quiz app and I am new to IOS.I want to get 3 wrong answers from an array of 6 wrong answers for a specific question and there will be 1 correct answer for each question.I want to randomize the wrong options every time the question is shown.So every time the question is shown the app will choose 3 wrong options from the array and 1 correct answer.How can I code this?I would be glad if you can help me on this.
Thank you..
{
int counted = [theOptions count];
int i;
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:counted];
for (i=0; i<counted; i++) [indexes addObject:[NSNumber numberWithInt:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:counted];
while ([indexes count])
{
int index = rand()%[indexes count];
[shuffle addObject:[indexes objectAtIndex:index]];
[indexes removeObjectAtIndex:index];
}
NSMutableArray* shuffledOptions = [[NSMutableArray alloc] initWithCapacity:4];
for (int i=0; i<counted; i++)
{
int randomIndex = [[shuffle objectAtIndex:i] intValue];
[shuffledOptions addObject:[theOptions objectAtIndex:randomIndex]];
UIButton* optionButton = [_optionsButtonsArray objectAtIndex:i];
optionButton.tag = randomIndex;
}
return shuffledOptions;
}
return theOptions;}
If you have an array of 6 wrong answers and want to randomly select three of them
NSArray *answers = [NSArray arrayWithObjects:#"Wrong #1", #"Wrong #2", #"Wrong #3", #"Wrong #4", #"Wrong #5", #"Wrong #6"];
NSMutableArray *output = [[NSMutableArray alloc] init];
int r;
while (output.count < 3) {
r = arc4random_uniform(5);
if (![output containsObject:[answers objectAtIndex:r]]) {
[output addObject:[answers objectAtIndex:r]];
}}
The easiest way would be select a random number between 0-5 then select another random one. If the next one is a duplicate of the first one repeat the previous step. Do this one more time and you now have three unique random numbers from 0-5.
A more clever way would be to store numbers 1-5 in an array. Shuffle the array and then return the first three indexes.
Good luck.

Resources