Reputation: 13
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!
Upvotes: 1
Views: 98
Reputation: 4113
This line is the reason:
index = (index - 1) - len * count;
As soon as count
is > 1, you're substracting a number bigger than the list length, resulting in a negative index. Removing the * count
should fix this.
Upvotes: 1