Sunday, March 29, 2015

what's wrong with my 'Josephus Problem' program?
































































































































Hey guys, good to see you, I'm a beginner of English and Java, so, I'm trying best to make myself clear...































































































































This's the original 'Josephus Problem' program, looks some troubles with it which gave me a WRONG answer, although it's totally OK if the 'Length' is much more short...I tried '5''6''10', it's alright.































































































































anyone can tell me where is the bug?































































































































THANK YOU A LOT!
































































































































































































Java Code:







































































































































public class Josefu
{
public static void main(String[] args)
{
Cycle cy=new Cycle();
cy.setLen(41);
cy.setPosi(1);
cy.setJump(3);
cy.creatCycle();
cy.play();

}
}
//
class Child
{
int no;
Child nextChild=null;
Child prevChild=null;
public Child(int no)
{
this.no=no;
}
}
//
class Cycle
{
int posi=0;
int jump=0;
int len=0;
Child firstChild=null;
Child fwdChild=null;
Child bwdChild=null;
public void setPosi(int posi)
{
this.posi=posi;
}
public void setJump(int jump)
{
this.jump=jump;
}
public void setLen(int len)
{
this.len=len;
}
//
public void creatCycle()
{
for(int i=1;i<=len;i++)
{
if(i==1)
{
Child cd=new Child(i);
this.firstChild=cd;
this.fwdChild=cd;
this.bwdChild=cd;
}
else
{
if(i==len)
{
Child cd=new Child(i);
fwdChild.nextChild=cd;
fwdChild=cd;
fwdChild.prevChild=bwdChild;
bwdChild=fwdChild;
fwdChild.nextChild=this.firstChild;
this.firstChild.prevChild=bwdChild;

}
else
{
Child cd=new Child(i);
fwdChild.nextChild=cd;
fwdChild=cd;
fwdChild.prevChild=bwdChild;
bwdChild=fwdChild;
}
}
}
}
public void play()
{
Child fwdChild=this.firstChild;
//
for(int p=1;p<posi;p++)
{
fwdChild=fwdChild.nextChild;
}
while(len!=1)
{
for(int j=1;j<jump;j++)
{
fwdChild=fwdChild.nextChild;
}
//
System.out.println(fwdChild.no);
fwdChild.prevChild.nextChild=fwdChild.nextChild;
fwdChild=fwdChild.nextChild;
this.len--;
}
//
System.out.println(fwdChild.no);
}
}




































































































































































































































































No comments:

Post a Comment