The challenge is to choose the best option at every moment of the game, following these rules:
You can select only the leftmost or rightmost card.
Your opponent ALWAYS chooses the first one, and ALWAYS chooses the highest card from the leftmost or rightmost card. If it is a tie, he will choose the rightmost one. Please note that this is not always the best choice.
Sometimes it’s impossible to win, but you must in any case display the highest level that you can add by playing against this opponent (or, say, strategy).
Example:
Cards: 1 2 4 2 8 4 3 Opponent: 3 4 2 2 = 11 Me: 1 8 4 = 13
Here I chose 1 instead of 4 on the second turn, so I could choose 8 later. Therefore, choosing the highest card is not always better.
I am trying to implement this solution using recursion, but I'm not sure if this is the best option. Any ideas on how to develop this algorithm?
[EDIT] Thanks @PengOne for this generous help. This is the code that is trying to implement, but unfortunately it gives me errors. What should I fix? I edit it as I go along.
static int cardGameValue(List<int> D, int myScore, int opponentScore) { if (D.Count == 0) return myScore; else { if (D[0] <= D[D.Count - 1]) { opponentScore += D[D.Count - 1]; D.RemoveAt(D.Count - 1); } else { opponentScore += D[0]; D.RemoveAt(0); } int left = cardGameValue( new List<int>(D.GetRange(1, D.Count - 1)), myScore + D[0], opponentScore); int right = cardGameValue( new List<int>(D.Take(D.Count - 2)), myScore + D[D.Count - 1], opponentScore); if (left >= right) { return left; } else { return right; } } }
source share