約瑟夫問題Java代碼
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()); }
} </pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!