Typical Index out of range Problem Can't see the issue

Hi there I’m trying to write a c# component in grasshopper.
I’m trying to find numbers that are following eachother in a List and that puts them into seperate branches of a tree Example: (0,5,6,7,2,5,4,3,4,5,6) to a tree with two branches {5,6,7} {3,4,5,6}.
How ever I have got a Index out of range Issue does.
I have m
Following numbers as tree branches.gh (7.9 KB)
aybe looked at it for to long and can’t find the issue. Any Ideas ?

for (int i = 0; i < SubList.Count; i++)
    {
      if (SubList[i] == 1) 
      {...}
      else if (SubList[i++] == 1) // WHY i++?
      {...}
      else if (SubList[i] != 1)
      {...}
    }

Here you are iterating with “for” up to SubList.Count … but, you are using i++ twice … so it surely will fall out of bounds.

1 Like

Thank you. :smiley: I wanted to make sure that I have will include the case where numbers are changing.
At least this was an easy fix.
int t = 0;
tree.Add(0, new GH_Path(t));

for (int i = 0; i < SubList.Count; i++)
{

  if (SubList[i] == 1)
  {
    tree.Add(IList[i], new GH_Path(t, i));
  }
  else if (i < SubList.Count && SubList[i++] == 1)
  {
    t = t + 1;
    tree.Add(IList[i], new GH_Path(t, i));
  }

}
  private void RunScript(List<int> IList, ref object A)
  {
    Grasshopper.DataTree<int> tree = new Grasshopper.DataTree<int>();
    int path = 0;
    List<int> temp = new List<int>();
    int n = IList.Count;
    if(n < 2)return;
    bool added = false;
    for(int i = 0;i < n;i++){
      if(temp.Count > 0){
        if(IList[i] - temp[temp.Count - 1] == 1){
          temp.Add(IList[i]);
          added = true;
        }
      }else if(i < n - 1 && IList[i + 1] - IList[i] == 1){
        temp.Add(IList[i]);
        added = true;
      }
      if(!added & temp.Count > 0){
        if(temp.Count >= 2){
          tree.AddRange(temp, new GH_Path(path));
          path++;
          i--;
        }
        temp = new List<int>();
      }
      added = false;
    }
    A = tree;
  }

Thank you that is a way smarter approch.
For anyone whos reading this later I had an acracy issue before and an out of range issue when using Math.Ads (a-b) < tolerance but I deleted the message.
This epic dude answered anyway :smiley: