Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Solved

Posted on 2000-02-13

I got this algorithm for a function that solves Josephus algorithm. and I will like to translate it to c++.

In C langiage:

#include <stdio.h>

#include <stdlib.h>

int josef(int num, int skip)

{

char *vec;

int i;

int curPtr;

int numLive = num;

vec = (char *)malloc(num+1);

for(i=1 ; i<=num ; i++)

vec[i] = 1;

curPtr = 1;

while(numLive > 1)

{

i = 1;

while(i<skip)

{

curPtr++;

if(curPtr > num)

curPtr = 1;

if(vec[curPtr])

i++;

}

vec[curPtr] = 0; /* KILL him*/

curPtr++;

if(curPtr > num)

curPtr = 1;

numLive--;

}

/* Find the one LIVE */

for(i=1 ; i<=num ; i++)

if(vec[i])

return(i);

return(-1);

}

What I have done so far in C++:

Jos(n,m)

for i=0 to n

{a[i]=i+1;}

while n>i do

for i=0 to n

{

if( a[i]!=0)

{

count=count+1;

if (count==m)

{

a[i]=0;

count=0;

}

}

}

I'm I doing it okay?

what else do I need?

In C langiage:

#include <stdio.h>

#include <stdlib.h>

int josef(int num, int skip)

{

char *vec;

int i;

int curPtr;

int numLive = num;

vec = (char *)malloc(num+1);

for(i=1 ; i<=num ; i++)

vec[i] = 1;

curPtr = 1;

while(numLive > 1)

{

i = 1;

while(i<skip)

{

curPtr++;

if(curPtr > num)

curPtr = 1;

if(vec[curPtr])

i++;

}

vec[curPtr] = 0; /* KILL him*/

curPtr++;

if(curPtr > num)

curPtr = 1;

numLive--;

}

/* Find the one LIVE */

for(i=1 ; i<=num ; i++)

if(vec[i])

return(i);

return(-1);

}

What I have done so far in C++:

Jos(n,m)

for i=0 to n

{a[i]=i+1;}

while n>i do

for i=0 to n

{

if( a[i]!=0)

{

count=count+1;

if (count==m)

{

a[i]=0;

count=0;

}

}

}

I'm I doing it okay?

what else do I need?

2 Comments

1,2,3,4,5,6,7

1,2,4,5,6,7

1,2,4,5,7

1,4,5,7

1,4,5

1,4

4

#include <stdio.h>

#include <stdlib.h>

int josef(int num, int skip)

{

char *vec = new char[num + 1];

int numLive = num;

for(int i=1 ; i<=num ; i++)

vec[i] = 1;

int curPtr = 1;

while(numLive > 1)

{

int i = 1;

while(i<skip)

{

curPtr++;

if(curPtr > num)

curPtr = 1;

if(vec[curPtr])

i++;

}

vec[curPtr] = 0; /* KILL him*/

curPtr++;

if(curPtr > num)

curPtr = 1;

numLive--;

}

int RetVal = -1;

/* Find the one LIVE */

for(int i=1 ; i<=num ; i++)

if(vec[i])

{

RetVal = i;

break;

}

delete [] vec;

return (RetVal);

}

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Course of the Month12 days, 5 hours left to enroll

Join the community of 500,000 technology professionals and ask your questions.