算法【一】约瑟夫问题

问题描述:n个人(编号0~(n-1)),从0开始报数,报到(m-1)的退出,剩下的人继续从0开始报数。求胜利者的编号。

公式法参考:https://blog.csdn.net/qq_25973267/article/details/50405616?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

https://blog.csdn.net/zxx2096/article/details/80142871

代码如下:


/**
 * 约瑟夫问题
 * n个人排成一圈,连续报数m,数到m的退出,问最后一个人的编号是谁
 */
public class Josephus  {

    /**
     * 方案一
     * @param n n是人数
     * @param m m是数字
     * @return
     */
    public static int lastIndexFirst(int n, int m) {
        boolean[] itemArray = new boolean[n];
        for(int i = 0; i < n; i ++) {
            itemArray[i] = false;
        }

        int amount = 0;
        int index = 0;
        while (amount < n - 1) {
            int cur = 0;
            while (cur < m) {
                index = index % n;
                if (!itemArray[index]) {
                    cur += 1;
                }
                index += 1;
            }
            amount += 1;
            index -= 1;
            itemArray[index] = true;
        }
        int result = -1;
        for(int i = 0; i < n; i ++) {
            if (!itemArray[i]) {
                result = i + 1;
                break;
            }
        }

        return result;
    }

    /**
     * 方案二:公式法
     * @param n
     * @param m
     * @return
     */
    public static int lastIndexSecond(int n, int m) {
        int s = 0;
        for (int i = 2; i <= n; ++i) {
            s = (s + m) % i;
        }

        return s + 1;
    }

    /**
     * 方案三
     * @param n n是人数
     * @param m m是数字
     * @return
     */
    public static int lastIndexThree(int n, int m) {
        boolean[] itemArray = new boolean[n];
        for(int i = 0; i < n; i ++) {
            itemArray[i] = false;
        }

        int amount = 0;
        int index = 0;

        int cur = 0;
        while (amount < n - 1) {
            if (!itemArray[index]) {
                cur += 1;
            }

            if (cur == m) {
                cur = 0;

                amount += 1;
                itemArray[index] = true;
            }

            index += 1;
            index = index % n;
        }
        int result = -1;
        for(int i = 0; i < n; i ++) {
            if (!itemArray[i]) {
                result = i + 1;
                break;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(Josephus.lastIndexFirst(10, 6));
        System.out.println(Josephus.lastIndexSecond(10, 6));
        System.out.println(Josephus.lastIndexThree(10, 6));
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值