Program to find winner of stone game in Python

PythonServer Side ProgrammingProgramming

Suppose Amal and Bimal are playing a game and Amal's turn is first. The game is like below −

There are n stones in a pile. Each player can take a stone from the pile and receive points based on the position of that stone. Amal and Bimal may value the stones in different manner.

We have two arrays of same length, A_Values and B_Values. Each A_Values[i] and B_Values[i] represents how Amal and Bimal, respectively, value the ith stone. Here whose score is maximum, he will be winner after all the stones are taken out. If there is a tie, the game results in a draw. Both players will play optimally. Both of them know the other's values. So if Amal wins, return 1. If Bimal wins, return -1. And for a draw match, return 0.

So, if the input is like A_Values = [2,4] B_Values = [3,5], then the output will be 1 because Amal will select second stone with point 4, so Bimal has only one chance to take first stone with point 3, but as Amal has greater score, so he wins.

To solve this, we will follow these steps −

  • n := size of A_Values
  • combinedValues := a new list
  • for i in range 0 to n, do
    • tmpV := A_Values[i] + B_Values[i]
    • insert pair (temV, i) into combinedValues at the end
  • sort the list combinedValues in reverse order
  • score_a := 0, score_b := 0
  • for i in range 0 to n - 1, do
    • curV := combinedValues[i]
    • if i mod 2 is same as 0, then
      • score_a := score_a + A_Values[curV[1]]
    • otherwise,
      • score_b := score_b + B_Values[curV[1]]
  • if score_a > score_b, then
    • return 1
  • otherwise when score_a is same as score_b, then
    • return 0
  • otherwise,
    • return -1


Let us see the following implementation to get better understanding −

def solve(A_Values, B_Values):
   n = len(A_Values)
   combinedValues = []
   for i in range(n):
      tmpV = A_Values[i] + B_Values[i]
      combinedValues.append([tmpV, i])


   score_a, score_b = 0, 0
   for i in range(n):
      curV = combinedValues[i]
      if (i % 2 == 0):
         score_a += A_Values[curV[1]]
         score_b += B_Values[curV[1]]

   if (score_a > score_b):
      return 1
   elif (score_a == score_b):
      return 0
      return -1

A_Values = [2,4]
B_Values = [3,5]
print(solve(A_Values, B_Values))


[2,4], [3,5]


Updated on 06-Oct-2021 11:01:28