N只猴子站成一行,每M只报数。
发布网友
发布时间:2024-10-22 07:51
我来回答
共2个回答
热心网友
时间:2024-10-24 08:31
import java.util.ArrayList;
import java.util.List;
public class Monkey {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int count = getN(args);
ArrayList list = (ArrayList) getList(count);
int M = 3;
String direction = "正";
int serial = M;
while (list.size() > 2 ) {
if ( serial < list.size()) {
System.out.println( direction + list.get(serial ) + "离队");
list.remove( serial );
serial = serial + M;
}else{
serial = serial - list.size();
list = (ArrayList) reversal(list);
direction = direction.equals("正") ? "反":"正";
}
}
System.out.println( list.get(1) + "是大王");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static List getList(int count) {
ArrayList list = new ArrayList();
for (int i = 0; i < count; i++) {
list.add(new Integer(i + 1).toString());
}
return list;
}
private static int getN(String[] args) throws Exception {
int count = 0;
try {
count = Integer.parseInt(args[0]);
} catch (Exception e) {
throw new Exception("请输入正确的猴子总数");
}
return count;
}
//反转数组中的顺序
private static List reversal(List list){
List newlist = new ArrayList();
for( int i = list.size() -1; i >= 0; i-- ){
newlist.add(list.get(i));
}
return newlist;
}
}
热心网友
时间:2024-10-24 08:22
哈哈,猴子选大王啊,以前用C++写的,现在JAVA是主了,用JAVA写了个,上面的较复杂
public class Kings {
public void selectKing(int num,int m) {
int count = 0;// 记录选出的猴子数
int[] a = new int[num];
// 初始化数组,每个元数代表一只猴子.
for (int i = 0; i < num; i++) {
a[i] = 1;
}
// 如果选出的猴子的个数是猴子总数-1则大王已经选出,跳出循环
int k = 0;
while (count < num - 1) {
for (int i = 0; i < num; i++) {
k += a[i];
// 选种的猴子出列(数组中体现:值变为0)
if (k == m) {
count++;
a[i] = 0;
k = 0;
}
}
}
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
System.out.println("Always you(gyh) are the first in my heard! But now,The king is "+ (i + 1) + "st!");
}
}
}
public static void main(String[] args) {
int num = 32;// 猴子的数量
int m = 3;// 循环基数
new Kings().selectKing(num,m);
}
}