Josephus' Circle

Here is my solution to the latest code contest from The Daily WTF Programming Praxis: Josephus’ Circle.

What I like about this solution is that it represents in code, how the problem is actually carried out in real life. The soldiers are counted off one by one.

Also, I just LOVE .Net generics!

static int Josephus(int numSoldiers, int soldiersToSkip)
{

     // create soldiers
     List<int> Soldiers = new List<int>();
     for (int i = 0; i < numSoldiers; i++)
     {
          Soldiers.Add(i);
     }

     // kill soldiers
     int iSoldier = 0;
     while (Soldiers.Count() > 1)
     {

          // skip ahead by the requested number of soldiers
          iSoldier = iSoldier + soldiersToSkip;

          // if we've gone over, then wrap back around to the top
          while (iSoldier > Soldiers.Count())
          {
               iSoldier -= Soldiers.Count();
          }

          // kill the choosen soldier
          Soldiers.RemoveAt(iSoldier - 1);
     }

     // return answer
     return Soldiers[0] - 1;

}
Bradley Dean's Picture

About Bradley Dean

Certified Xamarin Mobile Developer with experience in Xamarin Forms, Ionic, Cordova, Phone Gap, ASP.Net MVC, Web Services, and sarcasm.

Atlanta, GA http://truegeek.com