{
List<Integer> source = new ArrayList<Integer>();
List<Integer> out = new ArrayList<Integer>();
for(int i=1;i<=30; i++){
source.add(i);
}
int index=0;
while(source.size() > 0){
index = (index+4)%source.size();
out.add(source.get(index));
source.remove(index);
}
for(int i=0;i<out.size(); i++){
System.out.print(out.get(i) + " ");
}
}
-
补充:
-
结果是
5 10 15 20 25 30 6 12 18 24 1 8 16 23 2 11 21 29 13 26 7 22 9 28 19 17 27 4 14 3
其他回答(3)
有点难
.编程题:设有n个人依围成一圈,从第1个人开始报数,数到第m个人出列,然后从出列的下一个人开始报数,数到第m个人又出列,…,如此反复到所有的人全部出列为止。设n个人的编号分别为1,2,…,n,打印出出列的顺序;要求用java实现。(Core Java)
答:代码如下:
package test;
public class CountGame {
private static boolean same(int[] p,int l,int n){
for(int i=0;i<l;i++){
if(p[i]==n){
return true;
}
}
return false;
}
public static void play(int playerNum, int step){
int[] p=new int[playerNum];
int counter = 1;
while(true){
if(counter > playerNum*step){
break;
}
for(int i=1;i<playerNum+1;i++){
while(true){
if(same(p,playerNum,i)==false) break;
else i=i+1;
}
if(i > playerNum)break;
if(counter%step==0){
System.out.print(i + " ");
p[counter/step-1]=i;
}
counter+=1;
}
}
System.out.println();
}
public static void main(String[] args) {
play(10, 7);
}
}
public class Out {
public static int PERSON_COUNT = 30;//总人数
public static int[] getPers(int count) {
int[] temp = new int[count];
for(int i = 1; i <= count; i++) {
temp[i-1] = i;
}
return temp;
}
public static void main(String[] arg) {
int[] pers = getPers(PERSON_COUNT);//初始化数组
boolean[] out = new boolean[PERSON_COUNT];//标识该下标的人是否出列
int[] newPers = new int[PERSON_COUNT];//按出列顺序排列的新数组
//i标识遍历总人数的下标, n表示1到5的数字,count表示多少人出列了
for(int i = 0, n = 1, count=0; i < pers.length; i++) {
//如果该下标的人出列了
if(!out[i]) {
//如果数到5
if(n == 5) {
newPers[count] = pers[i];//将该下标的人加入到底count个出列数组
out[i] = true;//标识该下标的人已经出列
count++;//出列总数+1
n = 0;//数字从新开始数
}
n++;
}
//如果到了人数末尾,从新开始遍历
if(i+1 == pers.length) i = -1;
//如果全部出列
if(count == pers.length) {
break;
}
}
for(int i = 0; i < newPers.length; i++) {
System.out.println("第" + (i + 1) + "个出列的人是:" + newPers[i]);
}
}
}
测试已经通过,输出结果:
第1个出列的人是:5
第2个出列的人是:10
第3个出列的人是:15
第4个出列的人是:20
第5个出列的人是:25
第6个出列的人是:30
第7个出列的人是:6
第8个出列的人是:12
第9个出列的人是:18
第10个出列的人是:24
第11个出列的人是:1
第12个出列的人是:8
第13个出列的人是:16
第14个出列的人是:23
第15个出列的人是:2
第16个出列的人是:11
第17个出列的人是:21
第18个出列的人是:29
第19个出列的人是:13
第20个出列的人是:26
第21个出列的人是:7
第22个出列的人是:22
第23个出列的人是:9
第24个出列的人是:28
第25个出列的人是:19
第26个出列的人是:17
第27个出列的人是:27
第28个出列的人是:4
第29个出列的人是:14
第30个出列的人是:3