package ccnu;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo05 {
public static void main(String[] args) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("c:/users/" + System.getenv("username") + "/desktop/d.txt")));
int[] nPersons = josephus(7, new int[]{3, 1, 2, 8, 2, 1, 5});
StringBuffer sb = new StringBuffer();
for(int del : nPersons){
sb.append(del + " ");
}
byte[] data = sb.toString().trim().getBytes();
bos.write(data);
bos.flush();
bos.close();
}
public static int[] josephus(int n) {
if(n <= 0){
return null;
}
int[] delSerials = new int[n];
int index = 0;
Node rear = create(n);
Node p = rear;
int m = 3;
while (p.next != p) {
for (int i = 1; i < m; i++) {
p = p.next;
}
delSerials[index] = p.next.data;
index++;
p.next = p.next.next;
}
delSerials[index] = p.data;
return delSerials;
}
public static int[] josephus(int n, int[] nPersons) {
if (n <= 0 || nPersons == null || nPersons.length != n) {
return null;
}
int index = 0;
Node rear = create(n);
Node p = rear;
int m = nPersons[index];
m = m % n == 0 ? m : m % n;
while (p != p.next) {
for (int i = 1; i < m; i++) {
p = p.next;
}
nPersons[index] = p.next.data;
n--;
m = nPersons[++index];
m = m % n == 0 ? m : m % n;
p.next = p.next.next;
}
nPersons[index] = p.next.data;
return nPersons;
}
public static Node create(int n){
if(n <= 0){
return null;
}
Node head = new Node(1);
Node p = head;
int i = 2;
while(i <= n){
Node tmp = new Node(i++);
p.next = tmp;
p = tmp;
}
p.next = head;
return p;
}
private static class Node{
private int data;
private Node next;
public Node(int data){
this.data = data;
}
}
}