AceInfinity
Emeritus, Contributor
Genghis Kahn, being in a good mood decides to spare one life of his 1,000 captives. He has them stand in a circle and runs a sword through every second man.
If the first man is #1, which man will be left alive?
This is an interesting exercise, I had fun with it, creating a loop version and a recursive version. The loop version removed the person who was killed immediately, while the recursive one iterated through all the survivors and determined which were to be killed, and did it at once per recursive call.
I had fun, and it took a little bit of thinking to accomplish. I had a nice little bug that took me a while to figure out. The reason was that I didn't break down the rules first, which would become the comments of the code. I just jumped in and it taught me a lesson: Even a seemingly simple application can be complicated if you don't follow the proper steps.
I will post the code for both versions in a follow-up, but I figured I would give everyone here a chance at it first.
The big key is that he has them stand in a circle, and keeps going until there is only one person left.
I seen this posted on someone's article space on another site. So I took a swing at it... Turned out to be pretty easy lol. Here was my C++11 solution:
Read More:
Code:
[NO-PARSE]#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v(1000);
std::iota(v.begin(), v.end(), 1);
std::rotate(v.begin(), v.begin() + 1, v.end());
do
{
v.erase(v.begin());
std::rotate(v.begin(), v.begin() + 1, v.end());
} while (v.size() > 1);
std::cout << v.front() << std::endl;
}[/NO-PARSE]
I'd suggest others try it on their own first before seeing the solution I came up with.
:thumbsup2:
Last edited: