"Where would you stand to save your life?"
Here is a simple problem. Go ahead and try to solve it...
In an island are stranded 100 people and you are one among them. You were captured by tribals, who say that only one among the 100 can survive. And here is the condition. One of you is given an axe. And he has to hack and kill the guy to his right, and pass the axe to the guy after him. And the cycle continues...
So, if the people were numbered 1, 2, 3.... 100, then 1 kills 2, and gives to 3. 3 kills 4 and gives it to 5 and so on. The 99th guy kills 100th guy and passes it back to 1, who kills number 3 and so on. The question is, if you were in that group, where would you stand to be the last man standing?
And the solution is... *Spoiler Alert*
There are 3 ways of solving this.
One, is by finding a pattern. Do it for groups of 1, 2, 3 and so on... say till 10.
If the group had 1 guy, survivor = 1Just continue, you will see the pattern. For every number where the value is equal to 2 to power of n, as in 1, 2, 4, 8... the survivor is person 1. For any other number, the survivor is = 1 + (2 times the difference between the nearest two power number).
If the group had 2 guys, survivor = 1
If the group had 3 guys, survivor = 3
If the group had 4 guys, survivor = 1
If the group had 5 guys, survivor = 3
If the group had 6 guys, survivor = 5
If the group had 7 guys, survivor = 7
If the group had 8 guys, survivor = 1
The answer by the way is 73rd position...
Programming! We played this game just to come up with answers... The following are the 3 solutions each one of us came up with in a different language...
Solution in Python (Shortest program written by co-worker Amod Pandey, but took the most time to finish :P)
Solution in Ruby, which I wrote - I finished second, I have some trace statement for help :
And this is what I wrote subsequently...
Subsequent vastly improved solutions by Niyaz - One line solutions!!
And one more in Python
And then I solved this using Linked Lists
Apparently this problem is called Josephus problem. My friends Goutham Kamath and Prashanth Harshangi knew the problem along with a really fancy solution - they have provided the link to a PDF file here