public static int removeNM(int n, int m) {
LinkedList ll = new LinkedList();
for(int i = 0; i < n; i++)
ll.add(new Integer(i+1));
int removed = -1;
while(ll.size() > 1) {
removed = (removed + m) % ll.size();
ll.remove(removed--);
}
return ((Integer)ll.get(0)).intValue();
}
public static void main(String[] args) {
System.out.println(removeNM(3,2));
}
好像 private static int removeNM(int n, int m) {
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i = 0; i < n; i++)
ll.add(new Integer(i));
int lastSelected = 0;
while(ll.size() > 1) {
lastSelected = (lastSelected + m) % ll.size();
ll.remove(lastSelected--);
}
return ll.get(0).intValue();
}
private static int removeNM(int n, int m) {
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i = 0; i < n; i++)
ll.add(new Integer(i));
int lastSelected = 0;
while(ll.size() > 1) {
lastSelected = (lastSelected + m) % ll.size();
ll.remove(lastSelected--);
}
return ll.get(0).intValue();
}
public static void main(String[] args) throws Exception {
System.out.println(removeNM(100,4));
}
/**
* Josephus Problem
*
* Given a group of N men arranged in a circle under the edict that every Mth
* man will be executed going around the circle until only one remains, find the
* position in which you should stand in order to be the last survivor (Ball and
* Coxeter 1987).
*
* @author protozz
*
*/
public class Josephus {
private static int n;// the number of person
private static int m;// the interval
private static int INDEX_BEGIN = 1;
public Josephus(int num, int interval) {
if (interval >= num)
throw new InvalidParameterException();
n = num;
m = interval;
}
private void showQueue(Person head) {
Person p = head;
System.out.print(head.index + "->");
head = head.next;
while (head != p) {
System.out.print(head.index + "->");
head = head.next;
}
System.out.println();
}
public int getLast() {
Person head = initQueue();
showQueue(head);
int counter = 0;
while (counter != n - 1) {
for (int i = 1; i < m - 1; i++) {
head = head.next;
}
head.next = head.next.next;
head = head.next;
System.out.print(counter + ":");
showQueue(head);
counter++;
}
return head.index;
}
private Person initQueue() {
Person p = new Person(INDEX_BEGIN);
Person head = p;
for (int i = 0; i < n - 1; i++) {
p.next = new Person(p.index + 1);
p = p.next;
}
p.next = head;