'Can someone explain me why it throws an ArgumentOutOfRangeException?

static List<object> JosephusPermutation(List<object> items, int k)
{
  List<object> solution = new List<object>();
  int index = k - 1;
  int len = items.Count;
  int count = 1;
  foreach(object i in items){
    if(index<len){
      solution.Add(items[index]);
      index += k;
    }
    else{
      index = (index - 1) - len * count;
      count++;
    }
  }
  return solution;
}

I tried to create a function that takes every k element in the array and get an OutOfRangeException and don't know why it's happening. Can you explain me why these piece of code behaves like these? Appreciate your help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source