While loop not stopping with given criteria - iphone

Im having a bit of a problem with this while loop. I keep getting a crash because it continues to execute the loop even when it has found the object and supposedly increased the int.
Any ideas I have plenty of other loops set up in a similar way and they all work fine.
int possible = 0;
while (possible < [possibleAthetes count]) {
if ([[[possibleAthetes objectAtIndex:possible]valueForKey:#"ID"]intValue] == [self.athleteID intValue]) {
[possibleAthetes removeObjectAtIndex:possible];
possible = [possibleAthetes count] ;
}
possible ++;
}

You are incrementing possible even when you remove an object. Break out of the loop.
If you need to get rid of multiple athletes, leave out the break(No need to increment because of the removed object).
int possible = 0;
while (possible < [possibleAthetes count]) {
BOOL criteriaMatch = ([[[possibleAthetes objectAtIndex:possible]valueForKey:#"ID"]intValue] == [self.athleteID intValue]);
if (criteriaMatch){
[possibleAthetes removeObjectAtIndex:possible];
break;
} else {
possible++;
}
}

Related

Dataset or Statistics Mode

I expected this question to have a really straightforward answer but can't seem to find anything in the documentation.
I need to be able to get the mode of a dataset or a statistics element. All I can find is min, max, mean and median.
Is there no function that gives the mode?
Thank you
I ended up using the below function, but I still find it weird that the mode function is not built-in...
int maxCount=0;
for(int i=0; i<QueueLengthDailyMaq.size(); ++i)
{
int count=0;
for(int j=0; j<QueueLengthDailyMaq.size(); ++j)
{
if(QueueLengthDailyMaq.getY(j) == QueueLengthDailyMaq.getY(i))
{
count++;
}
if(count > maxCount)
{
maxCount = count;
mode = QueueLengthDailyMaq.getY(i);
}
}
}

How to fix : The object of type 'GameObject' has been destroyed but you are still trying to access it ? -Unity

I made a 5 second time bar to replace the wave. when wave1 has been 5 seconds it will move to wave2. then the first wave will be destroyed. when I got to wave3, an error came out. here's my code:
IEnumerator ChangeWave()
{
for (int i = 0; i < wave.Length - 1; i++)
{
yield return new WaitForSeconds(5f);
Destroy(wave[i]);
wave[i+1].SetActive(true);
}
}
the error said The object of type 'GameObject' has been destroyed but you are still trying to access it. - unity
sorry for my bad english.
There's a few things going on here.
Remove the -1 in the for loop, so it iterates to end
wave[i+1] will cause an error, so check if (i < wave.Length -1)
Destroy( array[index] ) will try and access Game Object but it's destroyed, so you should create a temporary var to hold gameobject, and set null to the array element.
Some fixes below - there might be a better way, but this is what I use:
Version 1 - Using the above fixes
IEnumerator ChangeWaveV2()
{
for (int i = 0; i < wave.Length; i++)
{
yield return new WaitForSeconds(.2f);
var t = wave[i];
wave[i] = null;
Destroy(t);
if(i < wave.Length - 1)
wave[i + 1].SetActive(true);
}
}
Version 2 - A variation without needing to null out the element and create a temporary var. If you iterate from end to front of the array, you can freely Destroy() GameObjects in an array. May not be useful as it changes the wave array.
IEnumerator ChangeWaveV3()
{
System.Array.Reverse(wave);
for (int i = wave.Length - 1; i >= 0; i--)
{
yield return new WaitForSeconds(.2f);
Destroy(wave[i]);
if(i > 0)
wave[i - 1].SetActive(true);
}
}

Linked List Parameterized constructor

I tried to do a Parameterized constructor for a linked list my program is about to implement a queue by using a liked list so i want to do a parameterized constructor like Queue(int value , int size) and it dose not run or doing a list
this is my code for this problem
Queue(int value,int _size)
{
for(int i = 0; i < _size; ++i)
{
Node* temp = new Node;
temp->data = value;
temp->next = nullptr;
if(head == nullptr)
{
head = tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}
}
i expected that the result is to fill the lest by value times size like if i run this function Queue x(20,3) the linked list should be
20 20 20
Since that this is a constructor, The head and tail are not properly initialized to use them. I would suggest adding head = tail = nullptr just before the loop and see what happens.
Follow this code after your node creation. I hope this will work. And do use i++ instead of ++i, as the later will make the loop for size-1 times.
if(head == NULL)
head = temp;
else{
Node *x;
x= head;
while(x->next != NULL)
x = x->next;
x->next = temp;
}

Using Block with objectAtIndex method of NSArray

Here is the code:
TrailLayer * layer = (TrailLayer*)[_layers objectAtIndex:(int)^{
if (_segmentNumber < [_segmentArray count]) {
return _segmentNumber;
} else {
return _segmentNumber - 1;
}
}];
what is the problem here? Here, all the _Variables are IVARs. I am first time using Blocks, can someone help me identifying this problem. Its giving EXC_BAD_INSTRUCTION here.
Thanks.
Try this code, First write block to get the index number, and use that number to retrieve value from array
int (^segmentIndex)(int) = ^(int segmentNumber){
if (segmentNumber < [_layers count]) {
return segmentNumber;
} else {
return segmentNumber - 1;
}
};
NSLog(#"Trail Layer %#", [_layers objectAtIndex:segmentIndex(_segmentNumber)]);
TrailLayer * layer = (TrailLayer*)[_layers objectAtIndex:segmentIndex(_segmentNumber)];
A block is a runnable thing like a function, basically a piece of code that you can store, pass around, and run later (or not). You want to pass an integer to objectAtIndex:, so passing a block makes absolutely no sense whatsoever.
What you could have meant to do was run the block, and then pass its result to objectAtIndex:. In that case, you would have to run the block:
TrailLayer * layer = [_layers objectAtIndex:^{
if (_segmentNumber < [_segmentArray count]) {
return _segmentNumber;
} else {
return _segmentNumber - 1;
}
}()]; // <-- run the block
However, defining a block (which is a full-fledged object, and does a lot of fancy stuff) just to run it immediately is kinda silly. If you want to just be able to use a piece of code as an expression, you could use the "statement expressions" language extension supported by both GCC and LLVM:
TrailLayer * layer = [_layers objectAtIndex:({
int result;
if (_segmentNumber < [_segmentArray count]) {
result = _segmentNumber;
} else {
result = _segmentNumber - 1;
}
result;
})];
But really you should just do a regular C conditional expression in this case:
TrailLayer * layer = [_layers objectAtIndex:
_segmentNumber < [_segmentArray count] ?
_segmentNumber : _segmentNumber - 1];

Counter in while within while not working

I'm having a strange problem with the following code:
int c = [whatsNewArray1 count];
int t = [dames count];
int i = 0;
int o= 0;
NSMutableArray *finalWhatsNew = [[NSMutableArray alloc]init];
while (i<c){
NSLog(#"teller array %i", i);
while(t>o){
NSLog(#"dames %i", i);
if ([[[dames objectAtIndex:o] productId] isEqualToString:[whatsNewArray1 objectAtIndex:i]]){
[finalWhatsNew addObject:[dames objectAtIndex:o]];
NSLog(#"inner dames%i", i);
}
o++;
}
i++;
}
This code retrieves al the entries from the "dames" array which are stated in the "finalWhatsNew" array. Problem with this is that the if is only get called the first time.
To make it a little bit clearer, the whole code is working fine, but as soon "i" is ++ to 1. the if statement isn't called. It looks like ios i canceling it out after the first time for performance reason or somethins like that. Anybody has any ideas?
Thnx!!!
After inner loop is finished for the first time the o counter is equal to array's count and so it won't enter the loop again. To make it work you must reset o counter on each iteration of the outer loop:
while (i<c){
o = 0;
while (t > o)
...
Edit: For clearer code (and probably better performance) you can use fast enumeration instead of usual for/while loops:
for (NSString *searchId in whatsNewArray1){
for (YourObject *obj in dames){
if ([[obj productId] isEqualToString:searchId])
[finalWhatsNew addObject: obj];
}
}
Edit2: Also you can eliminate 2nd loop by using NSPredicate to filter your array:
for (NSString *searchId in whatsNewArray1){
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"productId == %#",searchId];
[finalWhatsNew addObjectsFromArray:[dames filteredArrayUsingPredicate:predicate]];
}
As Vladimir says, you need to reset o after each iteration of the outer loop. Ideally you switch to for-statements here, as they fit what you're doing exactly:
for (int i=0; i<c; ++i) {
// ...
for (int o=0; o<t; ++o) {
// ...