ジョセフリングの一方向ループチェーンテーブルのJava実装
ジョセフ問題(ジョセフ置換とも呼ばれる場合もある)は、コンピュータ科学と数学に現れる問題である.コンピュータプログラミングのアルゴリズムでは,類似の問題をジョセフループとも呼ぶ.人々は処刑を待つ輪に立っている.カウントは、円の指定された点から始まり、指定された方向に円の周りに行われます.指定された数の人をスキップした後、次の人を実行します.残りの人に対してこの過程を繰り返し、次の人から同じ方向に同じ数の人をスキップし、一人だけが残るまで釈放される.
5人で円環を作り、2人目を最初に殺して前回殺した人の次から新しい円環を作り、2人目を殺して...最初の5人が残る3番まで
public class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
}
public class TestJoseph {
//
public static Node createLinkList(int n) {
Node head = new Node(1);
Node pre = head;
for (int i = 2; i < n + 1; i++) {
Node newNode = new Node(i);
pre.next = newNode;
pre = newNode;
pre.next = head;
}
return head;
}
//
public static void printLink(Node root) {
StringBuilder out = new StringBuilder();
Node cur = root;
while (true) {
out.append(cur.value).append(" ");
if (cur.next == null || cur.next == root) {
break;
}
cur = cur.next;
}
System.out.println(out);
}
public static void main(String[] args) {
//
int n = 5;
//
int m = 2;
// 1 , ,
if (m == 1) {
System.out.println(n);
} else {
Node head = createLinkList(n);
printLink(head);
Node pre = null;
Node cur = head;
//
while (cur.next != cur) {
for (int i = 0; i < m - 1; i++) {
pre = cur;
cur = cur.next;
}
pre.next = cur.next;
cur.next = null;
cur = pre.next;
printLink(cur);
}
}
}
}
1 2 3 4 5
3 4 5 1
5 1 3
3 5
3
5人で円環を作り、2人目を最初に殺して前回殺した人の次から新しい円環を作り、2人目を殺して...最初の5人が残る3番まで