您的位置:首页 > 编程语言 > Java开发

韩顺平老师的JAVA教学视频:解决约瑟夫问题

2010-06-03 14:15 627 查看
感觉挺好的,就贴出来给大家看看吧

 

关于约瑟夫问题:

这是17世纪的法国数学家加斯帕在《数目的游戏问题》中讲的一个故事:15个教徒和15
个非教徒在深海上遇险,必须将一半的人投入海中,其余的人才能幸免于难,于是想了一个办法:30个人围成一圆圈,从第一个人开始依次报数,每数到第九个人
就将他扔入大海,如此循环进行直到仅余15个人为止。问怎样排法,才能使每次投入大海的都是非教徒。

 

public class yuesefu {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("约瑟夫问题");
CycLink cyclink=new CycLink();
cyclink.setLen(9);
cyclink.createLink();
cyclink.setK(5);
cyclink.setM(3);
cyclink.show();
cyclink.play();
}
}
class Child{
int no;
Child nextChild=null;
public Child(int index)
{
//定一个编号
this.no=index;
}
}
class CycLink{
Child firstChild=null;//指向第一个人
Child temp=null;//跑龙套
int len=0;//表示多少个人
int k=0;//从第几个人开始数数
int m=0;//数几下
//设置链表大小
public void setLen(int len)
{
this.len=len;
}
public void setK(int K)
{
this.k=K;
}
public void setM(int M)
{
this.m=M;
}
//设置环形链表
public void createLink()
{
for(int i=1;i<=len;i++)
{
if(i==1)
{
//创建第一个人
Child ch=new Child(i);
this.firstChild=ch;
this.temp=ch;
}else
{
//创建最后一个人
if(i==len)
{
Child ch=new Child(i);
temp.nextChild=ch;
temp=ch;
temp.nextChild=this.firstChild;
}else
{
//继续创建
Child ch=new Child(i);
temp.nextChild=ch;
temp=ch;
}
}
}
}
//打印链表
public void show(){
Child temp=this.firstChild;//跑龙套
System.out.print("人数编号:");
do{
System.out.print(" "+temp.no);
temp=temp.nextChild;
}while(temp!=this.firstChild);
System.out.println();
}
//开始play
public void play()
{
Child temp=this.firstChild;
//1.找到开始数数的人
for(int i=1;i<k;i++)
{
temp=temp.nextChild;
}
System.out.print("从第"+this.k+"个人开始,数"+this.m+"的人依次是:");
while(this.len!=1)
{
//2.数m下
for(int j=1;j<m;j++)
{
temp=temp.nextChild;
}
//3.将数到m的人删除链表
Child temp2=temp;
System.out.print(" "+temp2.no);
//数到m的人继续往下走,走到数到m-1的那个人,将m-1的下一跳指向m的下一跳
while(temp2.nextChild!=temp)
{
temp2=temp2.nextChild;
}
//将m-1的下一跳指向m的下一跳,即删除数到m的人
temp2.nextChild=temp.nextChild;
temp=temp.nextChild;
this.len--;
}
System.out.println();
System.out.println("剩下的是:"+temp.no);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java class string 游戏