问题:n = 7人坐在一圈,从1开始报数,报到m = 20的人出列,将他的密码作为新的m,直到所有的人出列。密码依次为:3、1、7、2、4、8、4。
使用JAVA数组实现:
public static void main(String[] args) {
int m = 20;
Character[] people = {'A','B','C','D','E','F','G'};
int length = people.length;
int num = length;
Integer[] password = {3,1,7,2,4,8,4};
int index = 0;
int position = 1;
while (num > 0) {
if (m == position) {
num --;
System.out.print(people[index]);
System.out.print('\t');
people[index] = null;
position = 0;
m = password[index];
}
index = (++index % length);
if (people[index] != null) {
position ++;
}
}
}
使用LinkedList实现:
public static void main(String[] args) {
char[] p = {'A','B','C','D','E','F','G'};
int[] w = {3,1,7,2,4,8,4};
List<Character> people = new LinkedList<Character>();
List<Integer> password = new LinkedList<Integer>();
for (int i = 0; i < w.length; i++) {
people.add(p[i]);
password.add(w[i]);
}
int index = 0 ;
int position = 1;
int num = people.size();
int m = 20;
while (num > 0) {
if (position == m) {
System.out.print(people.remove(index));
System.out.print('\t');
m = password.remove(index);
num --;
position = 1;
if (index >= people.size()) {
index = 0;
}
} else {
if (num > 0) {
if (index >= people.size() -1) {
index = 0;
} else {
index ++;
}
position ++;
}
}
}
}
上面是我的实现方法。一定还有更好的解决方法。欢迎大家指点。