日期:2014-05-20  浏览次数:20626 次

编写一个小算法
有500个小朋友编号1-500 围成一圈,做1-3数数小游戏。 数到3的时候 那位小朋友推出,一直循环,算出最后一个小朋友的编号。

------解决方案--------------------
Java code

package com.zf.test;

import java.util.LinkedList;
import java.util.List;

public class Test3 {
    
    //虚拟 n 个children
    public List<Integer> buildChildren(int childrenSize){
        List<Integer> children = new LinkedList<Integer>();
        for (int i = 1 ; i <= childrenSize; i++) {  
            children.add(i);
        }
        return children;
    } 
    
    
    //递归计算
    public int calc (int currentNo , int currentListIndex , List<Integer>  children){
        if(currentListIndex == children.size()){
            if(children.size() > 1){
                currentListIndex = 0 ;
            }else{
                return children.get(0);  
            }
        }
        
        if(currentNo == 3){
            children.remove(currentListIndex);
            currentNo = 1;
        }else{
            currentNo++;
            currentListIndex++;
        }
        return calc(currentNo , currentListIndex , children) ;
    }

    //包装
    public int run( int childrenSize){
        return calc(1 , 0 , buildChildren(childrenSize));
    }
    
    public static void main(String[] args) {
        
        Test3 t = new Test3(); 
        System.out.println("最后退出的小朋友为:" + t.run(500));       
        
    }
    
}