Josephus Permutation

13 篇文章 0 订阅
6 篇文章 0 订阅

 https://www.codewars.com/kata/5550d638a99ddb113e0000a2

This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege.

Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act).

Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea.

You are now to create a function that returns a Josephus permutation, taking as parameters the initial array/list of items to be permuted as if they were in a circle and counted out every k places until none remained.

Tips and notes: it helps to start counting from 1 up to n, instead of the usual range 0..n-1; k will always be >=1.

For example, with n=7 and k=3 josephus(7,3) should act this way.

[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out and goes into the result [3]
[1,2,4,5,7] => 6 is counted out and goes into the result [3,6]
[1,4,5,7] => 2 is counted out and goes into the result [3,6,2]
[1,4,5] => 7 is counted out and goes into the result [3,6,2,7]
[1,4] => 5 is counted out and goes into the result [3,6,2,7,5]
[4] => 1 is counted out and goes into the result [3,6,2,7,5,1]
[] => 4 is counted out and goes into the result [3,6,2,7,5,1,4]

So our final result is:

josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4]

 约瑟夫问题,n个人围成一个圈,开始从1报数,123,123,123的这样报数,报到3的人被杀死,问最后剩下哪个人,需要将杀死的人的顺序输出。

我的算法:

缺陷:出局的人虽然被标记了,但是每次还得参与一次循环,到后期循环都是白走几次;

def josephus(items,k):
    result = []
    index = 0
    for _ in range(len(items)):
        count = 0
        while count<k:
            # 如果不是出局的人,次数加1
            if items[index] != -1:
                count += 1
            if count == k:
                result.append(items[index])
                # 每次出局的人都设置为-1
                items[index] = -1
            # 因为是个环,所以需要和长度求余数,计算出下一次的索引
            index = (index+1)%len(items)
    return result

 

大神的算法:

很巧妙的将出局人的索引算出来了

def josephus(items,k):
    result = []    
    count = 0
    while len(items)>0:
        # 出局的人的索引是 i+k-1,因为需要循环报数,所以需要和数组长度求余
        count = (count + k -1)%len(items)
        result.append(items.pop(count))
    return result

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值