n只猴子选大王,方法如下:按照1,2,3....n给猴子编号,然后按编号顺序坐成1圈,从1号猴子开始按编号顺序报数至m,报到m的猴子退出圈外,退出的猴子的下一只猴子重新从1开始报数至m,报到m的猴子退出,如此循环直至剩下一只猴子就是大王。要求编写一程序,n和m都是入参,返回最后一只猴子的编号。
代码
import java.util.*;
class Monkey
{
int index;
Monkey(int i)
{
index = i;
}
}
public class Monkeys
{
ArrayList monkeys = new ArrayList();
public Monkeys(int nMonkeys)
{
for (int index =1;index<=nMonkeys;index++)
{
monkeys.add(new Monkey(index));
}
}
public Monkey selectKing(int m)
{
int startIndex = 0;
while(monkeys.size() != 1)
{
int removeIndex = (startIndex + m-1) % monkeys.size();
monkeys.remove( removeIndex );
startIndex = removeIndex;
}
return monkeys.get(0);
}
public static void main(String[] args)
{
int[] params = {0,0};
if (!checkArgs(params, args)) return;
Monkeys monkeys = new Monkeys(params[0]);
System.out.println("The King of Monkeys is No."+
monkeys.selectKing(params[1]).index + "!");
}
private static boolean checkArgs(int[] result, String... args)
{
if (args.length < 2)
{
System.out.println("You must give me the number of
Monkeys and max value of count by argument.");
return false;
}
else if (args.length >2)
{
System.out.println("Two many arguments. Please pass only
two arguments");
return false;
}
int index = 0;
for (String s : args)
{
try
{
int x = 0;
try
{ x = Integer.parseInt(s);}
catch (NumberFormatException e)
{
NumberFormatException e1 =
new NumberFormatException(e.getMessage()
+ "/nInput argument must be decimal
digits");
throw e1;
}
if (x<=0)
{
NumberFormatException e =
new NumberFormatException("For input
string /""+s+"/"." + "/nArgument
must be > 0.");
throw e;
}
result[index++]=x;
}
catch (NumberFormatException e)
{
System.out.println("One argument is invalid.
Check it!");
System.out.println(e.getMessage());
return false;
}
}
return true;
}
}
运行结果
java Monkeys 10 5
The King of Monkeys is No.3!
java Monkeys 3 2
The King of Monkeys is No.3!
java Monkeys 8 4
The King of Monkeys is No.6!
java Monkeys 20 9
The King of Monkeys is No.6!