S
S
samsungovetch2018-08-19 15:50:40
Python
samsungovetch, 2018-08-19 15:50:40

How to solve the Joseph problem?

def josephus1(ls, skip):
    skip -= 1
    idx = skip
    while len(ls) > 1:
        if idx+1 > len(ls):
            idx %= len(ls)
        print(ls.pop(idx),"выбывает")
        idx = (idx + skip) % len(ls)
        print(idx,"Это IDX")
    print('survivor: ', ls[0])

def josephus2(ls, skip):
    skip -= 1
    dead_num = 0
    while len(ls) > 1:
        dead_num = (dead_num+skip) % len(ls)
        print(ls.pop(dead_num),"выбывает")
    print('survivor: ', ls[0])


n = int(input('Введите количество человек:'))
m = int(input('Сколько человек посчитать?:'))
list_people = [i for i in range(1, n + 1)]
print(list_people)

josephus(list_people, m)

Natural numbers n, m are given. It is assumed that n people stand in a circle and get numbers, counting counterclockwise, 1, 2, ..., n. Then, starting from the first person, the m-th person is also counted counterclockwise (since people are standing in a circle, the first person is behind the n-th person). This person leaves the circle, after which, starting from the next one, the m-th person is counted again and so on until only one person remains from the whole circle. Determine his number.
I solved the problem, searched the Internet, found the first two algorithms - josephus1 and 2. Is there any other way to solve it more conveniently or are these better? I just figured it out for a long time, but I didn’t come up with a better one. I thought to make it through the counter so that each m value was deleted, but it didn’t work out, the wrong numbers were deleted there and I scored and deleted it.
And yet - how to adapt the algorithm to a different number of people that you consider? That is, first 5, then 3, then 7, well, you understand. Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mentor2, 2018-08-19
@mentor2

See Graham, Knuth, Patashnik "Concrete Mathematics", World 2006, p 25

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question