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

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

Title | # Comments | Views | Activity |
---|---|---|---|

Modify static variables within a class in VC++ | 3 | 95 | |

cb: unreferenced local variable | 11 | 72 | |

Fast, free, private online code repository / editor | 7 | 90 | |

Which Linux flavors will this run on? | 6 | 77 |

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

Connect with top rated Experts

**21** Experts available now in Live!