We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Game Theory
- Bob and Ben
- Discussions
Bob and Ben
Bob and Ben
Sort by
recency
|
8 Discussions
|
Please Login in order to post a comment
Here is Bob and Ben problem solution in Python Java C++ and c programming - https://programs.programmingoneonone.com/2021/07/hackerrank-bob-and-ben-problem-solution.html
C# (as usually short - 1 line - and elegant, no indexing):
Python must be 1-ne as well........
simple java solution, O(1) space and O(number of trees) time
This is good problem for learning game theory. Hope my comments help you:
The key to this problem is Grundy Theorem wich sounds like:
or in more simple way:
So, we need now find all Grundy nunbers (shortly nimbers) and XOR all of them.
Grundy nunber (or nimber or Gn) definition:
Let's now find nimbers of our game. First we need to devide or game into sub games. in this case each subgame is tree in given forest. The trees looks like this one where nuber of child nodes depend on given k:
We need to highlight following properties of tree:
-if number of nodes N>2, then we can remove either one leaf or whole tree N --> N-1 or N --> 0.
-but when N=2, then both nodes become leafs, in this case we can remove only one of the leaf N --> N-1
Back to our nimbers:
if thre is N=0 nodes in tree
if N=1, then we can move only to 0-position,
if N=2, we can move only to 1 position
if N=3 we can move to 0-position or to 2-position:
if N=4 we can move to 0-position or to 3-position:
if N=5 we can move to 0-position or to 4-position:
if N=6 we can move to 0-position or to 5-position:
...and so on. We can see that:
for n =0 and n =2: G(n) = 0
for all other n: Gn(n) = (n-1)%2+1
Now we can calculate Grundy numbers (nimbers) for a tree of any height. And we only need to find XOR of all trees in given forest.
Below is my JavaScript solution passed all the tests: