学生数数,数到3就退出问题等等,问,原来是多少?或者知道剩下3个人,问原来这三个人的本来的学号是多少?
In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation.Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this:josephus_survivor(7,3) => means 7 people in a circle;one every 3 is eliminated until one remains[1,2,3,4,5,6,7] - initial sequence[1,2,4,5,6,7] => 3 is counted out[1,2,4,5,7] => 6 is counted out[1,4,5,7] => 2 is counted out[1,4,5] => 7 is counted out[1,4] => 5 is counted out[4] => 1 counted out, 4 is the last element - the survivor!The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata.
方法:
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class JosephusSurvivor {
public static int josephusSurvivor(final int n, final int k) {
List<Integer> people = new LinkedList<>();
for (int i = 1; i <= n; i++) {
people.add(i);
}
Iterator iter = people.iterator();
while (people.size() > 1) {
for (int i = 0; i < k; i++) {
if (!iter.hasNext()) {
iter = people.iterator();
}
iter.next();
}
iter.remove();
}
return people.get(0);
}
}