用java解决Josephus问题:

用java解决Josephus问题:

package edu.ch4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
* 已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。
* 从编号为k的人开始报数,数到m的那个人出列;
* 他的下一个人又从1开始报数,数到m的那个人又出列;
* 依此规律重复下去,直到圆桌周围的人全部出列。
*/
public class Josephus {
private int n;
private int m;

public void initnm(){
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);

try {
System.out.print("please in put n,m:");
String str=br.readLine();
String []stu=str.split(",");
this.n=Integer.parseInt(stu[0]);
this.m=Integer.parseInt(stu[1]);
while(m<0||m==1||m>n){
System.out.println("m shoud be smalller than n and bigger than 1!");
System.out.print("please in put m again:");
this.m=Integer.parseInt(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
public int getN() {
return n;
}
public int getM() {
return m;
}


public static void main(String[] args) {
CreateCircle cc=new CreateCircle();
cc.createc();
cc.showchild();

}

}
class Child{
int number;
Child nextchild=null;
Child(int num){
this.number=num;
}
}
class CreateCircle{
Child firstchild=null;
Child temp=null;
int Chilem;int Chilen;
Josephus jo=new Josephus();
public void createc(){
jo.initnm();
this.Chilem=jo.getM();
this.Chilen=jo.getN();
for(int i=1;i<=jo.getN();i++){
if(i==1){
Child ch=new Child(i);
temp=ch;
firstchild=temp;
}else if(i==jo.getN()){
Child ch=new Child(i);
ch.nextchild=firstchild;
temp.nextchild=ch;
}else{
Child ch=new Child(i);
temp.nextchild=ch;
temp=ch;
}
}
}
public void showchild(){
int m=1;
Child p,q=null;
p=firstchild;
while(p!=p.nextchild){
if(m==this.Chilem){
System.out.println("out number:"+p.number);
q.nextchild=p.nextchild;
p=p.nextchild;
m=1;

}else{
q=p;
p=q.nextchild;
m++;
}
}
System.out.println("number:"+p.number);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值