Josephus Survivor

In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation.

Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this:

josephus_survivor(7,3) => means 7 people in a circle;
one every 3 is eliminated until one remains
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out
[1,2,4,5,7] => 6 is counted out
[1,4,5,7] => 2 is counted out
[1,4,5] => 7 is counted out
[1,4] => 5 is counted out
[4] => 1 counted out, 4 is the last element - the survivor!

The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata.

Notes and tips: using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1.

没什么可说的每隔k排除一个,暴力破解

public class JosephusSurvivor {
    public static int josephusSurvivor(final int n, final int k) {
        ArrayList<Integer> ini = new ArrayList<>();
        for (int i = 1;i <= n;i ++)
        {
            ini.add(i);
        }
        int index = k;
        int iniSize;
        while(ini.size() > 1)
        {
            iniSize = ini.size();
            ini = nextArr(ini,k,index);
            while(index <= iniSize)
            {
                index += k;
            }
            index = index - iniSize;
        }
        return ini.get(0);
    }
    public static ArrayList<Integer> nextArr(ArrayList<Integer> ini, int k, int index)
    {
        ArrayList<Integer> nextArr = new ArrayList<>();
        int count = 1;
        for (int i:ini)
        {
            if ((count == ini.size())&&(nextArr.size() == 0)){
                nextArr.add(i);
                break;
            }
            if (count ++ != index) {
                nextArr.add(i);
            }
            else {
                System.out.println(i + " is out");
                index += k;
            }
        }
        return nextArr;
    }
}
顺便附上大佬的递归解法,本人数学菜鸡是算不清楚了
import java.util.Arrays;

public class JosephusSurvivor {
  public static int josephusSurvivor(final int n, final int k) {
    if(n == 1)
      return 1;
    
    return (josephusSurvivor(n - 1, k) + k - 1) % n + 1;
  }  
}
@ ptran11 , Miia Lamia

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值