对于约瑟夫问题三种求解方法:
- 数组模拟
- 结构体模拟
- 数学递归
java集合约瑟夫问题第一版(数组模拟)
package txtt;
import java.util.*;
public class Josen {
private int m;
private int n;
private int step;
private List<Integer> josen = new ArrayList<>();
public Josen() {
}
public Josen(int m, int n) {
for(int i = 0;i<n;i++) {
josen.add(1);
}
this.step = m;
setM(m);
setN(n);
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public void printOut() {
int index = 0;
int lenth = josen.size();
while(lenth !=1) {
while(step>0) {
if(josen.get(index) == 1)
{
step--;
}
if(step>0)
index++;
if(index == n)
index = 0;
}
lenth--;
step = m;
josen.set(index, 0);
System.out.println("第"+(index+1)+"人出局");
}
while(josen.get(index)==0) {
index++;
}
System.out.println("幸存者"+(index+1));
}
}
第一次写的就是数组,和集合没啥关系,就套用了集合的一个容器,集合的简便方法都没用上。所以改一下(利用上集合的remove方法)
java集合约瑟夫问题第二版(数组模拟)
package txtt;
import java.util.*;
public class Josen {
private int m;
private int n;
private int step;
private List<Integer> josen = new ArrayList<>();
public Josen() {
}
public Josen(int m, int n) {
for(int i = 0;i<n;i++) {
josen.add(i);
}
this.step = m;
setM(m);
setN(n);
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public void printOut() {
int index = 0;
while(josen.size() !=1) {
while(step>0) {
step--;
if(step>0)
index++;
if(index >= josen.size())
index = 0;
}
josen.remove(index);
step = m;
System.out.println("第"+index+"人出局");
System.out.println(josen);
}
}
}