Saturday, January 15, 2011

Josephus Problem

Given n (number of people) and m (every mth person eliminated), this code returns the index of the last person to be eliminated.

Josephus on wiki
Josephus on Wolfram MathWorld

/* Josephus Problem */

#include <stdio.h>

#define CAL_UPTO     100000

int cq[CAL_UPTO + 1] ;

/* count e from p and return new p */
int move(int e, int p, int left, int n)
{
     if (e==0) e=left ;

     while (e>0) {
          if (p>n) p = 1 ;
          if (cq[p]==1) e-- ;
          p++ ;
     }

     if (--p>n) p=1 ;
     return p ;
}

/* out of n persons, eliminate every mth person */
/* returns the last survisor */
int compute(int n, int m)
{
     int i, p=1, e, left=n, j ;

     for (j=1; j<=n; j++) cq[j] = 1 ;

     while (left) {
          e = m%left ;
          p = move(e, p, left, n) ;
          if (!(p==0 || cq[p]==0)) cq[p] = 0, left-- ;
     }
     return p ;
}

int main()
{
     int i, j, n, k ;

     scanf("%d%d", &n, &k) ;
     printf("Survivor: %d\n", i, compute(n, k)) ;

     return 0;
}

No comments:

Post a Comment

Followers