推荐视频链接:http://video.tudou.com/v/XMjE3NTE5NTk5Mg==.html
package com.eponit.test;
import java.util.ArrayList;
/**
* 约瑟夫环问题
* 1.集合解决,能够移除
* 2.数组解决,可以置零
* @author Administrator
*
*/
public class Test2 {
public static void main(String[] args) {
//集合解决
getLuckByList(8,3);
//数组解决
int[] array={1,2,3,4,5,6,7,8};
getLuckByArray(array,3);
}
//数组解决
public static void getLuckByArray(int[] array,int n){
//定义一个指针,操作数组元素,
int poem=-1;
for(int i=0; i<array.length-1; i++){
for (int j = 0; j < n; j++) { //报n个数,就循环几次,循环结束的值赋零
poem++;
if(poem==array.length){ //如果越界,就将指针置零
poem=0;
}
while(array[poem]==0){ //如果该位置的值等于零,就顺延到下一位
poem++;
if(poem==array.length){
poem=0;
}
}
}
array[poem]=0;
}
for (int i = 0; i < array.length; i++) {
if(array[i]!=0){
System.out.println("数组,幸运数字: "+array[i]);
}
}
}
//集合解决
public static void getLuckByList(int peoplenum, int number) {
ArrayList<Integer> list = new ArrayList<Integer>();
//给集合初始化值
for(int i=1; i<=peoplenum; i++){
list.add(i);
}
//开始遍历
int count = 1;
for(int i=0; list.size()!=1; i++){ //只要集合中超过1,就要不断的移除
if(i==list.size()){
i=0;
}
if(count%number==0){
list.remove(i--); //集合移除元素后,会前移,如果不减减,就会跳过下个元素
}
count++;
}
System.out.println("集合,幸运数字: "+list.get(0));
}
}
输出结果:
集合,幸运数字: 7
数组,幸运数字: 7