Index out of range problem for merging two lists

Page 1 of 1

2 Replies - 720 Views - Last Post: 07 October 2012 - 09:38 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=294414&amp;s=909d5a6d345c975cb6b67c1bb95bc223&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

Reputation: 0
• Posts: 2
• Joined: 05-October 12

Index out of range problem for merging two lists

Posted 05 October 2012 - 09:46 AM

Hi guys, I have a problem where I have 2 lists, one of XYPoints and one of doubles. Both lists are sorted. The idea is to merge these two lists such that the result is another sorted list of XYPoints, with the double values as x values of new XYPoints at the right sorted locations. For the sake of simplicity lets assume the y values are 0. For example:

double list= {0, 2, 5, 11}
XYPoints list= {(1,0), (3,0), (4, 0), (7,0)}

Result needs to be a new XYPoints list= {(0,0), (1,0), (2,0), (3,0), (4,0), (5,0), (7,0),(11,0)}

I decided to merge the two lists as follows, but I keep getting a Index out of range exception, and I cannot figure out why.

Below is my code. Assume that the function InterpoalteIntensity returns 0. Also, the exception occurs on the line :
```if (pointList[i].XValue < values[j])
```
which is strange, because I check for i to be in bounds just above it :
``` if (i < pointList.Count)
```
and i is never less than 0;

```			List<XYPoint> resultList = new List<XYPoint>();

int i = 0;
int j = 0;

while (j < values.Count || i < pointList.Count)
{
if (i < pointList.Count)
{
if (pointList[i].XValue < values[j])
{
i++;
}
else
{
if (i == 0)
{
//// We cannot interpolate before the first point, add 0 intensity
}
else
{
double interpolatedIntensity = InterpolateIntensity(pointList[i - 1], pointList[i], values[j]);
}
j++;
}
}
else if (j < values.Count)
{
//// We cannot interpolate after the last point, add 0 intensity
j++;
}
else
{
break;
}
}

return resultList;

```

Is This A Good Question/Topic? 0

Replies To: Index out of range problem for merging two lists

Reputation: 0
• Posts: 2
• Joined: 05-October 12

Re: Index out of range problem for merging two lists

Posted 05 October 2012 - 09:54 AM

Oops sorry to waste time, I just figured it out. Very stupid mistake. forgot to check for when i is not yet max and j is max.

#3 PyroCybin

Reputation: 1
• Posts: 13
• Joined: 02-July 12

Re: Index out of range problem for merging two lists

Posted 07 October 2012 - 09:38 PM

If you use SortedSet this will be much easier, elements added to a SortedSet are automatically sorted. Since it appears you are using a custom datatype you should implement the IComparable interface in the XYPoint class so that XYPoints can be easily sorted.