How to find which player will win - algorithm

Two players play the following game. At the beginning of the game they start with n (1<=n<=100000) piles of stones. At each step of the game, the player chooses a pile and remove at least one stone from this pile and move zero or more stones from this pile to any other pile that still has stones. A player loses if he has no more possible moves. Given the initial piles, determine who wins: the first player, or the second player, if both play perfectly.

This is a variant of Nim. Understanding the solution to Nim should help you understand this game better.
For Nim, the game begins with n piles of stones. In turn, each player chooses one pile and removes at least one, possibly more, stone from the pile. The game ends when there are no more stones remaining.
The wikipedia article linked above has a nice explanation of the winning strategy, which involves computing the binary digital sum of the pile sizes. Read up on that, and you should be able to solve this variant.

First start off by analyzing the positions with known outcome - that would be the case when all stones are in a single pile. Then you have no other pile with at least one stone so you can not perform the second part of the move(this is assuming that even when you move 0 stones there still has to be another non-empty pile) so this is loosing position.
Now start analyzing from which positions can you get to the loosing positions. These will be your first round of winning positions.
First observation: as a move only affects two piles it is obvious that you can get to the loosing position only if you have exactly two piles. If you have only two piles you can always get to the loosing position by removing all the stones from one of them and thus this is a winning position.
So now you have to think about which are the positions that force you to make a move taking you to the found winning position. These again will be loosing positions(tip: I believe this is only the case where you have 3 piles with 1 stone each).
Continue this way and in the end you will come up with the final solution. I do not want to solve the whole problem for you as this will be of no good for your skills. Better come up with the solution on your own.
Hope this helps.
NOTE: if you are allowed to perform operations on a single non-empty pile i.e. if when moving zero stones you don't need another non-empty pile, then the initial loosing position is when you have no stones left at all and the initial winning position is when you have only one pile with any number of stones.

Related

Minimum steps for a chess knight to capture n pawns that are moving down simultaneously?

This is a homework question, but I don't really know how to go about tackling it and would appreciate any tips, as I haven't found any very similar problems online.
Basically, I have to come up with a program that takes in positions of a number N of pawns on a 8x8 chess board, and the position of a single knight, and then determine whether it's possible for the knight to capture every pawn (while moving in standard chess knight L-shaped fashion) and what is the minimum amount of moves to do so; moreover, every turn all the pawns move 1 square down the board simultaneously. If any of the pawns makes it to the last row, it is promoted into a queen and the knight loses immediately if it doesn't capture it as soon as it is promoted. The knight also loses if it ends a turn in a position where it is to be attacked by any pawn the next turn.
This seems similar to a knight's tour problem, but I'm not sure how to deal with the fact that the targets the knight has to go to are always moving and also making sure the knight doesn't get captured. I first tried solving it with backtracking which seems to be a common approach for this sort of chess problem, but I couldn't really come up with anything. Then what I thought of as a possible, if very inefficient, solution with dynamic programming was to solve the knight's tour problem for each possible starting square for the knight (maybe memoizing the results as a 64x64 array) and then whatever square the knight is on I would know the minimum amount of steps to get to any other square (where a pawn might be). With this I could check which, if any, pawns could be captured before the closest pawn to the bottom row is promoted to queen (by comparing the number of steps for the knight to reach the pawn to the number of steps for the pawn to reach the final row). However, this is not a perfect solution either, as memoizing the knight's tour in this manner would only save the minimum amount of steps taken and not the actual paths (which would presumably take up a lot of memory) and thus I wouldn't be able to check whether the knight is going to be captured by a pawn at some point during the path.
I would think that a breadth-first search would be fine.
The knight has at most eight possible moves at each position and there are at most seven turns before some pawn gets promoted. So that's at most about two million possibilities to search, but in practice there would be a lot fewer.
You only need about N+6 bits to describe a position (64 possible knight locations and a bit vector of which pawns are still alive). Since N cannot be more than eight (otherwise the knight can't capture them all before one gets promoted), you can keep track of all the seen positions and the immediate predecessor of each one with a vector of 16384 shorts.

Practicing interview questions and want to know how to approach this one aka algorithm

Saw this as an interview question would want to know the correct way to break this down that way I can understand the thought process and code it myself for practice. Also any advice on how to break down a problem.
"There is a n * n square board, there’s a new kind of game which is played on this board. there are pieces on the board which can only move horizontal and vertical any number of squares until it encounters an opponent piece, when it does so, it replaces the opponent piece at that position and the turn alternates. The input will contain a n * n matrix with 1,2 and 0 in the cells. ‘1’ denotes your pieces, ‘2’ denotes opponent pieces, and ‘0’ denotes free space. One of your pieces has fallen from the board and neither you nor your opponent remember its original position, so you collectively decide that you can place it anywhere you want to, so its upto you to place it at a position where you can maximize the number of opponent pieces you can cut. Output the x and y coordinates of such position. If multiple positions exists, output anyone."

Game puzzle, two players playing the game of replacing coin values

We have given, n coins with each having some face value k.
Now, there are two players, nick and james playing the game with alternating turn. In each turn, a player can choose any coin and replace it with more than one coins having sum of face value equal to replaced coin. Each of the new coins must be having same equal face value. Integer p is also given, which is the limit denotes that a player can't use the coin for replacement having face value less than p.
All players have given unlimited number of coins with unlimited face values.
So sample input will be n,k,p and where n is no. of coin with each face value is k and limit p is described above. If both play optimally, and nick starts first who will win the game. A player loose the game if he can't able to play its turn (means can't able to replace any of the coin).
Is it game of nim problem or DP? How can we solve this?
This is definitely the kind of game which Nim is the right way to think about: it is a two-player game, it is perfect information meaning both players know the full game state at all times, there is no element of chance, it is an impartial game meaning the same moves are available to both players, and you lose if you are unable to move. So the Sprague–Grundy theorem applies to this game; every position in the game is equivalent to a nimber. We can solve a position to find who will win given optimal play, by computing the nimber for the position; a position is a first-player-win if and only if the nimber is not zero.
However, that turns out to be completely unnecessary for this specific problem, because all of the coins in the starting position have the same value.
If there are an even number of coins, then player 2 wins by a mirror strategy. Match the coins in pairs, and then whatever move the opponent plays on one coin, mirror that move on the other one. Match the resulting coins in pairs and continue mirroring on them.
If there are an odd number of coins, then player 1 wins by splitting one of them into coins of the smallest possible value >= p, such that no more moves can be made on those coins. Then player 1 adopts the mirror strategy given above for the remaining coins, which there are an even number of.
There is a special case: if the coins' face value is already such that player 1 cannot make any move, then player 2 always wins, regardless of whether the number of coins is odd or even.
So the answer is: player 1 wins if and only if n is odd and k has a factor >= p. Clearly there is not going to be a more efficient solution.

How to calculate Heuristic values for minimax

I am developing a software for a board game (2 player) which has 10x4 cells and both the players have 9 pieces each. Initially, the pieces for player 1 will be at the top of the board and for player 2 all the pieces will be at the bottom of the board (similar to chess but a lot less complex!).
I have used MiniMax algorithm to calculate the next best move. Now, the algorithm itself seems to work fine. The problem that I am facing is in Heuristic value calculation.
If there is no best move found in the depth till I am searching (4 currently), my code simply takes the first step which it finds from the move list. That is probably because the score of all the moves are same till the depth of 4!
So, it just keeps stalling. Eg., it will move piece 1 from position A to B in 1st turn and in the 2nd turn it will move the same piece from position B to A.
It keeps on doing that until the opponent moves closer to my pieces.
Now, what I want would love to know is how do I make sure that if the opponent is NOT closing in, I do that instead of stalling.
Currently, I am calculating the heuristic values based on the difference between my pieces and opp pieces.
How to calculate the values such that those moves which lead to position closer to the opponent's pieces are selected? Appreciate your help! Thanks!

Optimal solution for traversing random grids on a board by 2 players

Consider an infinite 2D board. We have two players at points P1 and P2 on the board. They need to traverse a sequence of boxes on the board G1, G2, G3 .... Gn.
At the start only G1 is known. The coordinates of G2 to Gn are not known only after the box previous to it has been traversed. The players can move one at a time in one of the 8 possible directions on the board in unit time. We need to find the minimum time to traverse all required boxes using the two players.
The obvious solution is a greedy approach where the player nearer to the box that needs to be traversed moves towards it. Then we calculate the nearer player again for the next G. I feel a better solution exists to this problem that I cannot get my head around right now. Does a better solution exist?
I think as the board is infinite we should try to cover as much area with both players within n moves as possible (for every n). This way we maximize the abound of fields we can reach within n moves.
So my strategy would be:
Who is next to the next box?
Let this be P1.
Let P1 go to the box (shortest path) and go with the other player P2 in the directly opposite direction. This way we maximize the distance between the two players which minimizes the overlapping of the area they can reach in n steps. This way we maximize the coverage of the area the two players can reach in n steps for the next box.
Choosing the player closest to the next box is the best heuristic you can find.
Explanation: Whenever a new goal appears, there are only two options: Move player 1 or player 2 to the goal at the cost of the distance in fields. We also prefer a situation where players are far apart in contrast to close together. The most extreme case would be that both players are on the same field which is as good as having only one player. Since the playing field is infinite, being far apart is always better.
If this is correct, then you should ask yourself: Should I really choose the player being further away from the goal and end up in a situation where the players are closer together than they would have been if I had taken the other player?
Certainly not. In an infinite field, choosing the closest player helps with both, minimizing the current cost and improving the situation for the next goal (players far apart).
Since the problem is non deterministic, the solution must be heuristic.
The "price" at each turn is the number of moves taken in the turn. This can be PrN1 or PrN2 for the number of moves for player1 or player2 respectively in turn N.
The "score" at each turn can be thought of as the probability that a certain arrangement (the position of both players) after the moves will be a good arrangement for the rest of the turns.
You'd want to use an evaluation function that considers both price and score to make the decision.
The problem is, the only useful scoring function is one that is some function of the distance between the players (the larger the distance, the greater the chance of being closer to the next turns) and this is exactly in sync with the minimum price. Any choice that keeps the players as far apart as possible is necessarily the one that was cheapest to make.
What all that means if that the best algorithm is simply to move the closest player, which is the first instinct you had.
Had the board not been infinite, you could create a better scoring function, one that considers the probabilities of the next boxes which would give lower scores to arrangements that leave a player on the edges of the board.

Resources