Giorgio R
Giorgio R

Reputation: 97

For loop by intervals

This should be a very easy issue, but I am stuck.

I have an array representing a certain measure for each angle of a circle, so it has 360 elements. I have to check the minimum value of those measures in a neighbourhood of an angle +/- 10 degrees. This is a function,so the angle can change. The function is like this:

double MyClass::FindMin(int angle) {
  lower_limit = x-10;
  upper_limit = x+10;
  for(int i=lower_limit; i<upper_limit; i++) {
    //Find the minimum
  }
  return minimum;
}

If I the value of the angle is 300, the for cycle like will be this:

for(int i=290; i<310; i++)

The problem comes when the angle will be around 360:

for(int i=355; i<365; i++)

This clearly will not work because the array has 360 values.

Is there an elegant way to solve this problem?

Upvotes: 1

Views: 773

Answers (4)

Hubert Bratek
Hubert Bratek

Reputation: 1104

Well if I were you I would write sth like this(after taking comments into consideration :)

int numOfIterations = 0;
int minAngle = currentAngle + 350;
while(numOfIterations < 20) // as you want it from -10 to 10 from your angle
{ 
    minAngle = minAngle % 360; 
    doSomething(i);
    i++;
    numOfIterations++;
}

Upvotes: 0

SunKnight0
SunKnight0

Reputation: 3351

Despite the upvotes or downvotes none of the (pre-edited) answers using % take into account the fact that i can be negative.

Inside your loop use:

j=i<360?i:i-360;
j=i<0?i+360:i;

and use j for whatever you are using i for.

Upvotes: -1

Hunter McMillen
Hunter McMillen

Reputation: 61510

You can use the modulus operator to compute a new index j that wraps correctly:

double findmin(int angle) {
  int lower_limit = angle + 350;
  int upper_limit = angle + 370;
  double minimum = 0.0;

  for(int i = lower_limit; i < upper_limit; i++) {
    // compute a new index j that wraps using the modulus operator
    int j = i % 360;

    // find minimum using j 
  }

  return minimum;
}

Edit: Modified based on feedback from @EdHeal in the comments.

Upvotes: 4

Sheila de Pope
Sheila de Pope

Reputation: 103

You must have problems not only with angles around 360, but also with angles around 0. Also note that you've missed the "+10" angle. My suggestion is (developing Ajris's answer):

double MyClass::FindMin( int angle ) {
  int current_angle = ( x + 350 ) % 360;
  for( int i = 0; i < 21; ++i, ++current_angle ) {
    current_angle = current_angle % 360;
    //Find the minimum
  }
  return minimum;
}

Upvotes: 0

Related Questions