java写--约瑟夫环

快下班了正好手头活干完,就写了这个约瑟夫环,采用的是模拟的方式,如果有问题请给预指正。

import java.util.ArrayList;

/**

 * 约瑟夫环
 */
public class JosephApp {
public static void main(String[] args) {
ArrayList<Integer> men = create((int)(Math.random() * 100));
cyclic(men,(int)(Math.random() * men.size()) ,(int)(Math.random() * men.size()));
}
/**
* @param men     人群
* @param start   开始报数人的编号 (从0开始)
* @param outNum  出局数   (报数从1开始)
*/
public static void cyclic (ArrayList<Integer> men, int start, int outNum ) {
System.out.println("=============== 人数:" + men.size() + "  开始报数人的编号:" + start + "  出局数:" + outNum);
int startIndex = start;
while(men.size()> 0) {
int a = (startIndex + outNum -1) % men.size();
System.out.println("现有人数:" + men.size() +"  开始报数人的编号:" + startIndex + "开始数,到" + outNum + "人编号为 :"  + men.remove(a) + "出局");
if (men.size() != 0) {
startIndex = a % men.size();
}
}
}
/**
* 对人员进行编号(从0开始)
* @param manCnt  人数
* @return
*/
public static ArrayList<Integer> create (int manCnt) {
ArrayList<Integer> men = new ArrayList<Integer>();
for(int i= 0; i < manCnt; i++)
men.add(i);
return men;
}
}

猜你喜欢

转载自blog.csdn.net/zhaozhbcn/article/details/41700251