October 10, 2014

One Algorithm per day (C#): What would be the last element of index n=3 in a List of integer numbers

List elements = new List();
int m = 10;
int n = 3;
for(int i = 0; i < m; i++){
 elements.Add(i + 1);
}

int k = 0;
int elementsLeft = m;
int j = 0;

while (elementsLeft > 1){
 k++;
 j++;
 j = j % elementsLeft;
 
 if(k % n == 0){
  elements.Remove(elements[j]);
  k = 0;
  elementsLeft--;
 }
}

Console.WriteLine(elements[0]);

No comments: