Java解决约瑟夫问题的代码

2022/1/12 17:04:30

本文主要是介绍Java解决约瑟夫问题的代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

下边资料是关于Java解决约瑟夫问题的代码。

package com.hongqishi;

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());
}

}



这篇关于Java解决约瑟夫问题的代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程