约瑟夫环解法之递归和非递归

package com.uncle.array_test;

/**
 * 约瑟夫环
 *
 */
public class JosephusRound {

    //循环方式  参数 参加的人数  幸运数字
    public int josephusRound(int playersCount, int luckNumber) {

        //死亡状态的数组   true---自杀了   false---没死
        boolean[] players = new boolean[playersCount];
        //记录数到几了
        int count = 0;
        //记录死亡人数
        int deathCount = 0;
        //记录此时死亡的那个人的索引位置
        int index = 0;
        while (deathCount!=players.length) {
            for (int i = 0; i < players.length; i++) {
                //活着数数
                if (players[i] == false) {
                    count++;
                }
                //如果是幸运数字就自杀
                if (count == luckNumber) {
                    //死亡数加一
                    deathCount++;
                    //把死的那个人记录上
                    players[i] = true;
                    //数的数清零 从头数
                    count = 0;
                    //记录下此时死的那个人的索引
                    index = i;
                }
            }
        }
        return index;
    }

    /**
     *
     * @param playersNum
     * @param luckNum
     * @return
     *
     *
     */

    public int josephusRound1(int playersNum, int luckNum) {
        if (playersNum == 1) {
            return 0;
        }
        return (this.josephusRound1(playersNum-1,luckNum)+luckNum)%playersNum;
    }
    public static void main(String[] args) {
        JosephusRound josephusRound = new JosephusRound();
        //System.out.println(josephusRound.josephusRound(2, 3));
        System.out.println(josephusRound.josephusRound1(2,3));
    }
}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页