Josephus problem約瑟夫斯問題
public class Test {
public static void main(String[] args) {
//Josephus problem
CircularLinkedList circularLinkedList = new CircularLinkedList();
int childNums = 125;
circularLinkedList.addChild(childNums);
// circularLinkedList.showAllChild();
circularLinkedList.getOutFrequencyChildNode(10, 20, childNums);
}
}
class CircularLinkedList {
// declare first child
Child first = null;
/**
* 將小孩節點加入環形鏈接串列
* @param nums 加入的節點數
*/
public void addChild(int nums) {
// validate nums is valid
if (nums < 1) {
System.out.println("傳入的數量有誤!");
return;
}
// now current node is first child
first = new Child(1);
Child current = first;
for (int i = 2; i <= nums; i++) {
Child child = new Child(i);
// afterward add more child nodes
// current node point to next new node
current.setNext(child);
// current node move forward
current = current.getNext();
}
// current node point to first child node
current.setNext(first);
}
public void getOutFrequencyChildNode(int whichChildStart, int countTimes, int childNums) {
// validate whichChildStart is vaild or not
if (first == null || whichChildStart < 1 || whichChildStart > childNums) {
System.out.println("起始為第幾個小孩輸入有誤,請重新輸入");
return;
}
Child helper = first;
// helper node position: pre node of the get out node
// just move helper node to the end of node
do {
helper = helper.getNext();
} while (helper.getNext() != first);
// just move first node and helper node to (whichChildStart - 1) position
for (int i = 0; i < whichChildStart - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
while(true) {
// the circularLinkedList has only one node left
if (helper == first) {
break;
}
for (int i = 0; i < countTimes - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
// first node is get out node
System.out.printf("環形鏈接串列出圈小孩節點編號:%d\n", first.getNo());
// helper node points to the next of first node
first = first.getNext();
helper.setNext(first);
}
System.out.println("========================================");
System.out.printf("最後留在圈中的小孩節點編號:%d\n", helper.getNo());
}
/**
* 遍歷所有小孩節點
*/
public void showAllChild() {
if (first.getNext() == null) {
System.out.println("環形鏈接串列為空~");
}
Child temp = first;
do {
System.out.printf("當前小孩編號為%d\n", temp.getNo());
temp = temp.getNext();
} while (temp != first);// continue loop
}
}
class Child {
private int no;
private Child next;
public Child(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public Child getNext() {
return next;
}
public void setNext(Child next) {
this.next = next;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Child{");
sb.append("no=").append(no);
sb.append('}');
return sb.toString();
}
}
如有敘述錯誤,還請不吝嗇留言指教,thanks!