Best card choice in card game in C#

前端 未结 3 1551
遥遥无期
遥遥无期 2021-01-19 16:47

The problem consists in choosing the best option at every moment of the game following these rules:

  • You can only pick the leftmost or the rightmost card.

3条回答
  •  没有蜡笔的小新
    2021-01-19 17:06

    This is the code that actually worked in the end. Thanks to everyone for your support.

        static int cardGameValue(List D, int myScore, int opponentScore)
        {
            if (D.Count == 0) return myScore;
            else if (D.Count == 1)
            {
                opponentScore += D[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(D.GetRange(1, D.Count - 1)), myScore + D[0], opponentScore);
    
                int right = cardGameValue(new List(D.GetRange(0, D.Count - 1)), myScore + D[D.Count - 1], opponentScore);
    
                if (left >= right)
                {
                    return left;
                }
                else
                {
                    return right;
                }
            }
        }
    

提交回复
热议问题