这是一个有趣的算法问题,1,2报数问50人最后留下的是哪个人?
思路:这种报数分为两种形式一种围成一圈,另一种站成一排,前者每次都从头开始,后者首尾轮流报数
第一种情况代码如下
public class TwoByDie {
private static boolean c = true;
private static int max = 10;
private static int[] num;
/**
* @param args
*/
public static void main(String[] args) {
num = new int[max];
for (int i = 0; i < max; i++) {
num[i] = i + 1;
}
method(num, true);// 人,第一个是否为2,正序倒叙
}
private static void method(int[] nm, boolean is) {
for (int x = 0; x < nm.length; x++) {
System.out.print(nm[x] + " ");
}
int ss = nm.length;
boolean iss = (ss % 2 == 0 ? true : false);
int[] nmnm;
if (ss % 2 == 0) {
nmnm = new int[ss / 2];
} else if (!is) {
nmnm = new int[ss / 2];
} else {
nmnm = new int[ss / 2 + 1];
}
// if (((ss % 2 == 0) && is) || (ss % 2 == 1) && !is) {
// nmnm = new int[ss / 2];
// } else {
// nmnm = new int[ss / 2 + 1];
// }
// [ss/2+ (ss%2==0&&is)?0:1];
// System.out.println(nmnm.length+" 前集合nmnm");
// c=!c;
if (1 == ss) {
System.out.println("最后一个人是:" + nm[0]);
} else {
// 正序
System.out.println();
for (int i = is ? 0 : 1, j = 0; i < ss; i += 2, j++) {
nmnm[j] = nm[i];
}
// if(turn){
// //第一个为1
// if(is){
// for(int i=0,j =0;i<ss;i+=2,j++){
// nmnm[j] = nm[i];
// }
// }else{
// //第一个为2
// for(int i=1,j =0;i<ss;i+=2,j++){
// nmnm[j] = nm[i];
// }
// }
// }else{
// // System.out.println(ss-1+" 后续集合 ");
// // for(int x = 0 ;x<ss;x++){
// // System.out.println(nm[x]+" 后zhi ");
// // }
// if(is){
// for(int i=ss-1,j=0;i>=0;i-=2,j++){
// //System.out.println(j+" 后续集合 ");
// nmnm[j] = nm[i];
// }
// }else{
// //第一个为2
// for(int i=ss-2,j=0;i>=0;i-=2,j++){
// nmnm[j] = nm[i];
// }
// }
// }
method(nmnm, iss);// 人,第一个是否为2,正序倒叙
}
}
}
实现的方法很简单,只是为每次都新建的int数组附长度的时候想了一下
其实第二种场景就在注解里,有空我再好好把方法归结下来!
想这样的东西真的很好玩,此类文章未完待续!