Best card choice in card game in C#

前端 未结 3 1528
遥遥无期
遥遥无期 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:08

    Build the solution out from the simplest cases using recursion.

    Let D be the array of cards. Let A be the total of your cards and B be the total of your opponent's cards. Set S = A-B to be the value of the game. You win if S>0, lose if S<0 and tie if S==0.

    The easiest is to make two moves at once, your move followed by the opponent's determined move. There are two base cases to consider:

    • If length(D) == 0, return S. The game has ended.

    • If length(D) == 1, return S + D[0]. You choose the remaining card, and the game ends.

    For the recursive case, when length(D) > 1, evaluate the two possibilities

    • Let L be the result of the game if you choose the left card followed by the opponent doing his deterministic move, i.e.

      L = D[0] - max(D[1],D[N-1]) + cardGameValue(newD)

    • Let R be the result of the game if you choose the right card followed by the opponent doing his deterministic move, i.e.

      R = D[N-1] - max(D[0],D[N-2]) + cardGameValue(newD)

    Choose the play corresponding to the larger number, i.e. take D[0] if L>=R, otherwise take D[N-1]. Here N = length(D).

提交回复
热议问题