约瑟夫问题Java代码
2018-07-20 来源:open-open
public class JosephQuestion {
public static void main(String[] args) {
for (int i = 2; i < 11; i++) {
findMonitor(initPersons(i),i);
}
}
public static Person initPersons(int num) {
Person firstPerson = new Person(1);
Person lastPerson = firstPerson;
for (int i = 2; i <= num; i++) {
Person person = new Person(i);
lastPerson.setNextPerson(person);
lastPerson = person;
}
lastPerson.setNextPerson(firstPerson);
for (int i = 0; i <num; i++) {
System.out.print(firstPerson.getName()+" ");
firstPerson = firstPerson.getNextPerson();
}
System.out.println();
return firstPerson;
}
public static void findMonitor(Person person,int size) {
Person lastPerson = person;
int counter = 1;
while(size>1){
lastPerson = person;
person = person.getNextPerson();
counter++;
if(counter==3){
lastPerson.setNextPerson(person.getNextPerson());
person =lastPerson.getNextPerson();
counter=1;
size--;
}
}
System.out.println(person.getName());
}
}
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐