Countout (Round Robin) Game
It's suppose to take n children (imagine they are in a cirlce) and a prompted number (say 5) and starting from the 1st child and going round, count out every 5th child untill only one child is left in the ring.
For example for n=11, and coutout=5, the output is suppose to be 8.
for 10, 5, the output is suppose to be 3;
I get wrong numbers and it freezing though. Can't see what is wrong with the code either. The dry runs work well.
Code:
#include <stdio.h>
#include <conio.h>
int main(void) {
int ring[101]={0};
int x=0, count=0, cv, numchild, j;
int ringactive (int ring[], int size);
clrscr();
printf ("Enter number of chilren and countout value: ");
scanf ("%d %d", &numchild, &cv);
for (j=1; j<=numchild; j++)
ring[j]=1;
while ( ringactive(ring,numchild+1)==1) {
while (count<cv) {
if (x>=numchild) x=0;
x++;
if (ring[x]==0) x++;
else count++;}
ring[x]=0; count=0;}
for (j=1; j<=numchild; j++)
if (ring[j]==1) printf ("%d", j);
return 0;
}
int ringactive (int ring[], int size) {
int i, count=0;
for (i=1; i<size; i++)
if (ring[i]==1) count++;
if (count>1) return 1;
return 0; }
Re: Countout (Round Robin) Game
You need to rethink (and reformat) your code. Reformating like this will allow you and others to read the code easily and it's consistant:
Code:
#include <stdio.h>
#include <conio.h>
int main(void)
{
int ring[101]={0};
int x=0, count=0, cv, numchild, j;
// Following looks like a prototype and goes outside main()
int ringactive (int ring[], int size);
clrscr();
printf ("Enter number of chilren and countout value: ");
scanf ("%d %d", &numchild, &cv);
// Loops should go from 0 to < max -- fewer problems will occur
for (j=1; j<=numchild; j++)
ring[j]=1;
while (ringactive(ring,numchild+1)==1)
{
while (count<cv)
{
if (x>=numchild) x=0;
x++;
if (ring[x]==0) x++;
else count++;
}
ring[x]=0; count=0;
}
for (j=1; j<=numchild; j++)
if (ring[j]==1) printf ("%d", j);
return 0;
}
int ringactive (int ring[], int size)
{
int i, count=0;
for (i=1; i<size; i++)
if (ring[ i]==1) count++;
if (count>1) return 1;
return 0;
}
Your code seems to break down by ringactive() starting at 1 (first child), looping to beyond the last child, returning a 0 or 1 and having no idea after it returns what child was stopped on. Then starting all over again at 1. Also cv must be used in the routine.
count is a local variable in ringactive() and is never passed back to main() where count is also a local variable and is never changed from 0.
Rethink traversing the kid list (from 0 to < numchild). This includes actually using cv properly to get the proper child.
Also, output values at key places in the code to see if you're getting the values you need.
Re: Re: Countout (Round Robin) Game
Quote:
Originally posted by WaltP
// Following looks like a prototype and goes outside main()
int ringactive (int ring[], int size);
Not true. It is perfectly valid to prototype functions within functions. It's not common, but it is perfectly valid.
Quzah.