This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)
Task #1 this week is described as follows:
There are 50 people standing in a circle in position 1 to 50. The person standing at position 1 has a sword. He kills the next person i.e. standing at position 2 and pass on the sword to the immediate next i.e. person standing at position 3. Now the person at position 3 does the same and it goes on until only one survives.
Write a script to find out the survivor.
This is a well known theoretical exercise in computer science, by the name of the Josepheus problem, based on the story of Flavius Josephus, a Jewish historian in the first century.
Algorithm
To me, the most natural way to solve this problem is with a circular linked list. As a very quick review, a linked list is a list of items where each item also contains a pointer, reference, index, whatever to the next item in the list. A single element is usually drawn like this:
Continue reading “PWC 048 › Survivor (Josepheus problem)”