Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Josephus Problem

Sumit Rawal answered on May 18, 2023 Popularity 9/10 Helpfulness 1/10

Contents


More Related Answers


Josephus Problem

0

Children often play a counting-out game to randomly select one person from the group by singing a rhyme. The purpose is to select one person, either as a straightforward winner, or as someone who is eliminated.

Josephus problem is related to this concept. In this problem, people are standing in one circle waiting to be executed. Following points list the specifications of Josephus problem:

The counting out begins at a specified point in a circle and continues around the circle in a fixed direction.

In each step, a certain number of people are skipped and the next person is executed.

For example, if we have

n

people, and

1

k−1

people are skipped every time, it means that the

k

th person is executed. Here,

k

is the step-size.

Let’s discuss “Josephus Problem” through an example in the illustration below:

Circular Linked List: Josephus Problem

Step Size = 2

Move two steps fromthe beginningas specified by the step size. 1 willbe the starting point and so movingto 1 will be Step 1.

1 of 10

After having a look at the illustration, you’ll hopefully understand the Josephus Problem. For this lesson, we have to count out the nodes from the linked list one by one according to the step size until one node remains. To solve this problem, we will tweak the remove method from one of the previous lessons so that we can remove nodes by passing the node itself instead of a key. To avoid confusion, we’ll use the code from remove and paste it in a new method called remove_node with some minor modifications.

The modifications are as follows:

if self.head.data == key:

changes to

if self.head == node:

and

if cur.data == key:

changes to

if cur == node:

As you can see, instead of comparing the data of the node for a match, we compare the entire node itself.

You can check out the method below where the changed code is highlighted: 

Popularity 9/10 Helpfulness 1/10 Language whatever
Source: Grepper
Link to this answer
Share Copy Link
Contributed on May 18 2023
Sumit Rawal
0 Answers  Avg Quality 2/10


X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
X
Grepper Account Login Required

Oops, You will need to install Grepper and log-in to perform this action.