0

I am creating a function that creates a point in specific coordinates, which calls itself moving to each of the cardinal points (until a spicific limit).

I have a StackOverflowException error when more than 5000 positions are stored.

More easy: I have created points with coordinates moving only to the north and still giving the same error

*NorthLimit, LatitudeDeviation and LongitudeDeviation are constants.

public void CreatePosition(decimal latitude, decimal longitude)
{
    boolean end = true;

    Positions.Add(new Position(latitude, longitude));

    if (NorthLimit > (latitude + LatitudeDeviation))
    {
      CreatePosition(latitude + LatitudeDeviation, longitude);
      end = false;
    }

    if (end == true)
    {
      // It ends :)
    }
}

What measures should I take?

imj
  • 472
  • 1
  • 8
  • 24
  • 2
    I think this method doesn't do what you expect. For example, it will keep moving one step to the north, then one to the south (back to its starting point), then back to the north again, etc, forever. Did you mean for it to keep walking in each direction and only in that direction until it reaches the limits, i.e. `Positions` contains a "cross" shape? Or did you mean for it to find all positions in a grid within the bounds? – canton7 Mar 19 '19 at 16:30
  • 2
    I don't see how the recursion should end. It seems one of the `if`s will always be true so you keep recursing deeper and deeper into the the method until the return addresses flood your stack. `end = false;` is totally meaningless here as you never check it. – René Vogt Mar 19 '19 at 16:30
  • Is it intentional that these are no `if else` blocks? theoretically one call of `CreatePosition` could cause four additional calls of the same method. – nilsK Mar 19 '19 at 16:32
  • I'm not clear on what you want your output to actually *be*. Can you provide some sample input and output? – canton7 Mar 19 '19 at 16:34

1 Answers1

4

Responding to your edited question, where you're just moving north.

You'll need to convert your recursive algorithm into an iterative one. This can get quite complex - Eric Lippert has a fantastic blog series on different techniques (part 1, part 2) - but in your case it's simple.

public void CreatePosition(decimal latitude, decimal longitude)
{
    Positions.Add(new Position(latitude, longitude))

    for (decimal currentLatitude = latitude + LatitudeDeviation;
         currentLatitude <= NorthLimit;
         currentLatitude += LatitudeDeviation)
    {
        Positions.Add(new Position(currentLatitude , longitude));
    }
}
canton7
  • 37,633
  • 3
  • 64
  • 77