473,763 Members | 1,373 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help:the problem of Ring of Josephus

Hi,
I'm the beginner of the CPL.I write a program about the problem of Ring
of Josephus,using DoubleLinkList data structure.
I'm very confused that I think there is really no error in my
code.But,the compiler sometimes show some strange errors,sometime s can
pass through with an unknown trouble when it is running,and no
result.So,could anyone give me some help? Thank you very much!
Here is my code:
--------------------------------------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>

typedef struct DuLNode
{
int data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode,*DuLin kList;

int ex_16(int *,int,int);

int main(int argc, char *argv[])
{
int a[]={1,2,3,4,5,6,7 ,8,9,10,11,12,-1};//use -1 as the flag of
ending of the array
int n=8,k=5;
printf("The last number is %d",ex_16(a,n,k ));
return 0;
}

int ex_16(int *a,int n,int k)
{
DuLinkList L;
L=(DuLinkList)m alloc(sizeof(Du LNode));
L->data=0;L->next=L;L->prior=L;//create the DuLinkList with the
head-node

int *p=a;
while(*p!=-1)
{
DuLinkList DL;
DL=(DuLinkList) malloc(sizeof(D uLNode));
DL->data=*p;
DL->prior=L->prior;L->prior->next=DL;
DL->next=L;L->prior=DL;
L->data++; //L->data is the length of the List exclude the
head-node
p++;
}//initiate the DuLinkList

DuLinkList q;int i,temp;

while(1)
{
if(L->next!=L)
{
q=L;
for(i=0;i<(n-1)%L->data;i++)
{
q=q->next;
temp=q->data;
}
q->prior->next=q->next;
q->next->prior=q->prior;
free(p);
L->data--;
}
else break;

if(L->prior!=L)
{
q=L;
for(i=0;i<(k-1)%L->data;i++)
{
q=q->prior;
temp=q->data;
}
q->prior->next=q->next;
q->next->prior=q->prior;
free(p);
L->data--;
}
else break;
}//delete the node which is at the point

return temp;
}//ex_16
----------------------------------------------------------------------------------------------

Please tell any faults or wrong habits in my code.

Mar 5 '06 #1
17 5820
Yuri CHUANG said:
Hi,
I'm the beginner of the CPL.I write a program about the problem of Ring
of Josephus,using DoubleLinkList data structure.
That's probably a mistake right there. If you have a small amount of data,
an array will be just fine. For arbitrary amounts of data, Josephus is
probably better solved with a circular list rather than a linear one.
#include <stdio.h>
#include <stdlib.h>

typedef struct DuLNode
{
int data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode,*DuLin kList;
Hiding pointers in typedefs is always a bad idea. I'd much rather see a
function like DuLNode *addnode() than DuLinkList addnode() - it makes it
far clearer what's going on.

int ex_16(int *,int,int);

int main(int argc, char *argv[])
{
int a[]={1,2,3,4,5,6,7 ,8,9,10,11,12,-1};//use -1 as the flag of
ending of the array
Or simply calculate the number of elements in the array (it's equal to the
size of the array divided by the size of one member thereof), and then pass
this information to any function that needs it.
int n=8,k=5;
printf("The last number is %d",ex_16(a,n,k ));
return 0;
}

int ex_16(int *a,int n,int k)
{
DuLinkList L;
L=(DuLinkList)m alloc(sizeof(Du LNode));
The cast is meaningless. Fortunately, in your case, it doesn't conceal an
error - but it could have done. Much simpler: L = malloc(sizeof *L);

In the event that the allocation fails, by the way, your program heads off
into hyperspace. It doesn't just rely on the success of the allocation - it
/assumes/ the success of the allocation.
L->data=0;L->next=L;L->prior=L;//create the DuLinkList with the
head-node
For the second time, line-wrap makes a monkey of your comment syntax. The
old-fashioned /* comment style */ may be old-fashioned, but it is more
robust.

By the way, 0 isn't part of your input data, so why are you including it in
the list? As a node counter?

On the plus side, you're pointing L->next and L->prior at L, which makes me
think you did after all decide to go for circularity.
int *p=a;
while(*p!=-1)
{
DuLinkList DL;
DL=(DuLinkList) malloc(sizeof(D uLNode));
Why not just: DL = malloc(sizeof *DL);
DL->data=*p;
DL->prior=L->prior;L->prior->next=DL;
DL->next=L;L->prior=DL;
Yeah, that looks good so far.
L->data++; //L->data is the length of the List exclude the
head-node
p++;
}//initiate the DuLinkList

DuLinkList q;int i,temp;
Presumably you have a C99 compiler which understands all this mixed
declarations/code and //-style comment stuff? My compiler just calls them
syntax errors. In fact, all my compilers call them syntax errors.

while(1)
Surely you mean while(I haven't yet solved the Josephus problem)?
{
if(L->next!=L)
....i.e. if the list is not empty apart from the head node
{
q=L;
....point q to the head node
for(i=0;i<(n-1)%L->data;i++)
{
q=q->next;
....count n people round the ring...
temp=q->data;
}
q->prior->next=q->next;
q->next->prior=q->prior;
free(p);


p just points to your array, which you didn't malloc. You meant to free(q),
I think.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Mar 5 '06 #2

"Yuri CHUANG" <yu*******@126. com> wrote in message
news:11******** **************@ i40g2000cwc.goo glegroups.com.. .
Hi,
I'm the beginner of the CPL.I write a program about the problem of Ring
of Josephus,using DoubleLinkList data structure.
I'm very confused that I think there is really no error in my
code.But,the compiler sometimes show some strange errors,sometime s can
pass through with an unknown trouble when it is running,and no
result.So,could anyone give me some help? Thank you very much!
Here is my code:


I'd never heard of the "Ring of Josephus." So I looked it up.

For the actual "Ring of Josephus," n=13 and k=3. But, all rings stop on the
nth element. You have n=8, and k=5. Unfortunately, your ring won't stop on
the 8th element since the 13th element is -1, not the 8th. Also, you need
the nth element in the array, i.e., 13 is missing for n=13. You may want to
setup 'a' as a pointer, malloc() the space for it, and then fill it with 1
through n and -1.
Rod Pemberton
Mar 5 '06 #3
Well,it's question in my Chinese book,maybe there are translated
problems.
So,I describe it as follows:
There are integers from 1 to m,forming a circle.The number 1 is the
head.Delete the nth number in one direction,then delete the kth number
in the other,until there is only one number left.Print the last number.
e.g. n=12,m=8,k=5
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 9 10 11 12 //delete 8
1 2 3 4 5 6 9 10 11 12 //delete 7
1 2 3 4 5 6 9 11 12 //delete 10(8th location)
.....
1 4 6 9 11
4 6 9 11
4 6 9
4 9
4
so the result is 4.
The critical problem of my code is that I couldn't get any answer,even
error one.I think there must be wrong use of malloc function.
Give me some help,please.
Thanks a lot.

Mar 6 '06 #4
Well,it's question in my Chinese book,maybe there are translated
problems.
So,I describe it as follows:
There are integers from 1 to m,forming a circle.The number 1 is the
head.Delete the nth number in one direction,then delete the kth number
in the other,until there is only one number left.Print the last number.
e.g. n=12,m=8,k=5
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 9 10 11 12 //delete 8
1 2 3 4 5 6 9 10 11 12 //delete 7
1 2 3 4 5 6 9 11 12 //delete 10(8th location)
.....
1 4 6 9 11
4 6 9 11
4 6 9
4 9
4
so the result is 4.
The critical problem of my code is that I couldn't get any answer,even
error one.I think there must be wrong use of malloc function.
Give me some help,please.
Thanks a lot.

Mar 6 '06 #5
Well,it's question in my Chinese book,maybe there are translated
problems.
So,I describe it as follows:
There are integers from 1 to m,forming a circle.The number 1 is the
head.Delete the nth number in one direction,then delete the kth number
in the other,until there is only one number left.Print the last number.
e.g. n=12,m=8,k=5
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 9 10 11 12 //delete 8
1 2 3 4 5 6 9 10 11 12 //delete 7
1 2 3 4 5 6 9 11 12 //delete 10(8th location)
.....
1 4 6 9 11
4 6 9 11
4 6 9
4 9
4
so the result is 4.
The critical problem of my code is that I couldn't get any answer,even
error one.I think there must be wrong use of malloc function.
Give me some help,please.
Thanks a lot.

Mar 6 '06 #6

"Yuri CHUANG" <yu*******@126. com> wrote in message
news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
Well,it's question in my Chinese book,maybe there are translated
problems.
So,I describe it as follows:
There are integers from 1 to m,forming a circle.The number 1 is the
head.Delete the nth number in one direction,then delete the kth number
in the other,until there is only one number left.Print the last number.
e.g. n=12,m=8,k=5
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 9 10 11 12 //delete 8
1 2 3 4 5 6 9 10 11 12 //delete 7
1 2 3 4 5 6 9 11 12 //delete 10(8th location)
....
1 4 6 9 11
4 6 9 11
4 6 9
4 9
4
so the result is 4.
The critical problem of my code is that I couldn't get any answer,even
error one.I think there must be wrong use of malloc function.


The problem is too simple to use linked lists. This codes solves the
specific problem shown.
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
int value;
int flag;
} ring_el;

int main(void)
{
ring_el *ring;
int n,m,k;
signed int x,y,z;
int t;

n=12;
m=8;
k=5;

ring=malloc(n*s izeof(ring_el)) ;

for(x=0;x<n;x++ )
{
ring[x].value=x+1;
ring[x].flag=1;
}
for(y=0;y<(n-1);)
{
for(x=0,z=0;x<m ;)
{
if (ring[z].flag==1)
{
x++;
z++;
if(x>=n)
x=0;
if(z>=n)
z=0;

}
else
{
z++;
if(z>=n)
z=0;
}
}
y++;
if(y>(n-1))
break;
z--;
if(z<0)
z=n-1;
ring[z].flag=0;
for(t=0;t<n;t++ )
if(ring[t].flag)
printf("%2d ",ring[t].value);
else
printf(" . ");
printf("\n");
for(x=n-1,z=n-1;x>=(n-k);)
{
if (ring[z].flag==1)
{
x--;
z--;
if(x<0)
x=n-1;
if(z<0)
z=n-1;
}
else
{
z--;
if(z<0)
z=n-1;
}
}
y++;
if(y>(n-1))
break;
z++;
if(z>=n)
z=0;
ring[z].flag=0;
for(t=0;t<n;t++ )
if(ring[t].flag)
printf("%2d ",ring[t].value);
else
printf(" . ");
printf("\n");
}
for(x=0;x<n;x++ )
{
if(ring[x].flag)
printf("Answer: %d",ring[x].value);
}

exit(EXIT_SUCCE SS);
}
Rod Pemberton
Mar 7 '06 #7
Thank you,Rod

Mar 7 '06 #8
The problem is too simple to use linked lists. This codes solves the
specific problem shown.
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
int value;
int flag;
} ring_el;

int main(void)
{
ring_el *ring;
int n,m,k;
signed int x,y,z;
int t;

n=12;
m=8;
k=5;

Couldn't you have also gone like
int n = 12;
int m = 8;
int k = 5;
ring=malloc(n*s izeof(ring_el)) ;
Why don't we check malloc() for NULL? Is malloc() this special when it
comes to the Ring of Josephus
for(x=0;x<n;x++ )
{
ring[x].value=x+1;
ring[x].flag=1;
}
for(y=0;y<(n-1);)
{
for(x=0,z=0;x<m ;)
{
if (ring[z].flag==1)
{
x++;
z++;
if(x>=n)
x=0;
if(z>=n)
z=0;

}
else
{
z++;
if(z>=n)
z=0;
}
}
y++;
if(y>(n-1))
break;
z--;
if(z<0)
z=n-1;
ring[z].flag=0;
for(t=0;t<n;t++ )
if(ring[t].flag)
printf("%2d ",ring[t].value);
else
printf(" . ");
printf("\n");
for(x=n-1,z=n-1;x>=(n-k);)
{
if (ring[z].flag==1)
{
x--;
z--;
if(x<0)
x=n-1;
if(z<0)
z=n-1;
}
else
{
z--;
if(z<0)
z=n-1;
}
}
y++;
if(y>(n-1))
break;
z++;
if(z>=n)
z=0;
ring[z].flag=0;
for(t=0;t<n;t++ )
if(ring[t].flag)
printf("%2d ",ring[t].value);
else
printf(" . ");
printf("\n");
}
for(x=0;x<n;x++ )
{
if(ring[x].flag)
printf("Answer: %d",ring[x].value);
}

exit(EXIT_SUCCE SS);
}


Where is free()? Is the function off having an affair with teacher in
comp.lang.c++ ?
Rod Pemberton


Ohh..... my aching hips.

Mar 7 '06 #9

"Chad" <cd*****@gmail. com> wrote in message
news:11******** *************@u 72g2000cwu.goog legroups.com...
n=12;
m=8;
k=5;

Couldn't you have also gone like
int n = 12;
int m = 8;
int k = 5;


Yes. I could have. I could have also done this:
int n=12,m=8,k=5;

I specifically placed them in the open. It's very likely he'll replace them
with a scanf() etc.
Why don't we check malloc() for NULL? Is malloc() this special when it
comes to the Ring of Josephus
Do you _honestly_ think that malloc() will fail to provide 32 bytes? 4Kb?
64Kb? on any modern computer, miniframe or mainframe?

Do you _honestly_ think that he'll be running a 64Gb "Ring of Josephus"? In
that case, he'd definately want a linked-list.
Where is free()? Is the function off having an affair with teacher in
comp.lang.c++ ?


You don't understand what exit() must do to interface properly with an OS.
exit(EXIT_SUCCE SS);


The two important lines from the spec:
"The exit function causes normal program termination to occur."
"Finally, control is returned to the host environment."

Returning resources to an OS, such as deallocation of the memory allocated
by a program, is a mandatory part of the host OS's "normal program
termination" and "control ...[being] returned to the host environment."
Without it, the OS would run out of memory... Since all successful OS's
where partly developed or influenced heavily by EE's, I doubt that there is
a 'stupid' OS which doesn't deallocate memory.
Stop being inane.
Rod Pemberton
Mar 7 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
2084
by: Mark Richards | last post by:
I've been programming for many years, but have only recently taken a deep "C" dive (bad pun, i know) and need a lot of explanation from an expert. My questions center around those mysterious pointer beasties. The following code is excerpted from digitemp, a program that reads 1-wire devices. Digitemp is the work of Brian C. Lane. As I walk through this code, I have a number of questions. I'm hoping someone with experience in...
5
5191
by: Bill Cohagan | last post by:
I'm constructing an ASP app with a frameset on the home html page. From frame A I need to referesh the page in frame B when a button click occurs on a button in Frame A (server side event handler). To accomplish this I've included some client side script in the page being built in frame A such that whenever it is received by the browser it reloads frame B's page. The problem is that (sometimes) this sequence of events produces a dialog...
4
17969
by: astroboy | last post by:
Help! I run into error when my query is too long, anyway to solve this?? Dim objCommand As New OleDb.OleDbCommand(sql, objConn) Dim objDataAdapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(objCommand) intNumOfRec = objDataAdapter.Fill(objData)
8
2639
by: Xu, Wei | last post by:
Hi, I have wrote the following sql sentence.Do you have comments to improve the performance.I have created all the indexed. But it's still very slow.Thanks The primary key is proj_ID and Task_UID. SELECT PR.PROJ_NAME AS PRName, PR.PROJ_ID As PRProjID, PR.TASK_UID As PRTaskUID, 'Dev' AS GroupType, Feat.PROJ_ID As FeatProjID, Feat.TASK_UID As FeatTaskUID, Feat.FeatureID AS FeatureID,
0
836
by: Fabio | last post by:
"The program is in a invalid format, and cannot be run. It may be damaged" when I try to run it on Win98". I'm using VC 2003 with MFC. Thank's Fabio
7
10395
by: Aga | last post by:
Hi, I'm quite new in WebServices. I work in VS2003, C#. My code is : MyWebReference.ClassX x1=new MyWebReference.ClassX(); x1.Url="address to wsdl"; System.Net.NetworkCredential nc=new System.Net.NetworkCredential("user","password","domain");
1
1650
by: ALi Shaikh | last post by:
This works and shows the factors or tells if the number is a prime number but doesn't show ODD factors please help!! I need to turn this tomorrow #include <iostream> using namespace std; int prime(int num); int main() { int num; cout<<"Enter number: "; cin>>num;
2
1979
by: Shree | last post by:
I am having this confusion going on in my head for sometime now. The question is whether setting the object reference to null (nothing) help the GC in collection in anyway? Can anyone shed some light on this? Is there any way to validate this proposition? Or is it just a myth... -Thanks, Shree
6
8444
by: GiJeet | last post by:
Problem using AS operator to cast Tag property Hello, I’m using the Tag property of a menu item to hold an enum value of a PictureBoxSizeMode. Eg: this.menuImageStretch.Tag = System.Windows.Forms.PictureBoxSizeMode.StretchImage; now in the ProcessImageClick method I check to make sure the Tag propety is not null and cast from type Object to PictureBoxSizeMode
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9998
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3523
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2793
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.