有17个人围成一圈(编号0~16),从第0号的人开始从1报数,凡报到3的倍数的人离开圈子,然后再数下去,
测试你是否适合做程序员? http://bbs.tianya.cn/post-414-12360-1.shtml
<span style="font-family: Arial, Helvetica, sans-serif;">package abc;</span>
public class Loop{
public static int loopIndex = 0;
public int[] getout(int[] arrayIn){
int total = arrayIn.length;
if( total == 2) {
System.out.println("\n\nend!!!!!!!!!!the value=" + arrayIn[1]) ;
return new int[0];
}
//System.out.println("\n--------------------------total=" + total+ ",yu="+ total%3) ;
int[] arrayOut = new int[1];
int resultIndex = total - total/3;
if( resultIndex >= 1 ){
//System.out.println("-------------new resultIndex=" + resultIndex) ;
arrayOut = new int[resultIndex];
}
int j = 0;
int k = 0;
int yu = total%3;
for(int i=0;i<total;i++){
if( ((i+1) % 3) != 0) {
k = j + yu;
if( k >= resultIndex ){
k = k - resultIndex ;
}
arrayOut[k] = arrayIn[i];
//System.out.println("num "+ arrayIn[i] + " is in! origin index=" + i + ",new index="+ k );
j++;
}else{
//System.out.println("\nnum " + arrayIn[i] + " is out! ");
}
}
for(int i=0;i<arrayOut.length;i++){
System.out.print(" " + arrayOut[i] + ",");
}
System.out.println(" ");
//return new int[10];
loopIndex++;
return getout(arrayOut);
}
public static void main(String[] args){
int inputLength = Integer.parseInt(args[0]);
int[] a = new int[inputLength];
for(int i=0;i<inputLength;i++){
a[i]=i;
System.out.print(a[i]+",");
}
System.out.println(" ");
//System.out.println("A-----------------");
Loop lo = new Loop();
lo.getout(a);
}
}
另外一个算法,,特点是考虑整个记数是环形的,第一圈数完后,原先第一个的‘0'的新顺序是就是第17+1=18
package abc;
public class LP {
public static void main(String[] args) {
int inputLength = Integer.parseInt(args[0]);
int[] a=new int[ inputLength ];
int count=0;
int count2= inputLength;
while(count2>1)
{
int j=0;
while(j< inputLength){
if(a[j]==0)
{
count++;
if(count%3==0)
{
a[j]=1;
count2--;
System.out.println("出去的人是"+j + ",count=" + count);
}
}
j++;
}
System.out.println("----count2=" + count2 + ",count=" + count);
}
for (int i = 0; i < a.length; i++) {
if(a[i]==0)
System.out.println("剩下的人是"+i);
}
}
}