📜  游戏的最佳策略|特殊金币

📅  最后修改于: 2021-04-24 16:47:04             🧑  作者: Mango

给定一排银币,其中存在特殊的金币。有两个玩家在玩游戏,并且每走一步,一个玩家就必须从该行的左端或右端移走一个硬币,而移走特殊硬币的玩家将赢得这场比赛。任务是找到游戏的获胜者。

例子:

方法:通过一些示例可以观察到,如果银币的数量为奇数,则第一个玩家赢得游戏,否则第二个玩家赢得游戏。在特殊情况下,当金币在拐角处时,无论银币数量如何,第一个玩家都是获胜者。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the
// winner of the game
string getWinner(string str, int len)
{
      
    // To store the count of silver coins
    int total = 0;
      
    if(str[0]=='G' ||str[len-1]=='G')
        return "First";
    else{
        for (int i = 0; i < len; i++) {
  
            // Update the position of
           // the gold coin
            if (str[i] == 'S') {
                total++;
            }
        }
  
        // First player will win the game
        if ((total % 2) == 1)
            return "First";
        return "Second";
    }
}
  
// Driver code
int main()
{
    string str = "GSSS";
    int len = str.length();
  
    cout << getWinner(str, len);
  
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
  
class GFG
{
  
// Function to return the
// winner of the game
static String getWinner(String str, int len)
{
  
    // To store the count of silver coins
    int total = 0;
    for (int i = 0; i < len; i++) 
    {
  
        // Update the position of
        // the gold coin
        if (str.charAt(i) == 'S')
        {
            total++;
        }
    }
  
    // First player will win the game
    if ((total % 2) == 1)
        return "First";
    return "Second";
}
  
// Driver code
public static void main(String []args)
{
    String str = "GSSS";
    int len = str.length();
  
    System.out.println(getWinner(str, len));
}
}
  
// This code is contributed by Surendra_Gangwar


Python3
# Python3 implementation of the approach 
  
# Function to return the 
# winner of the game 
def getWinner(string, length) :
  
    # To store the count of silver coins 
    total = 0; 
    for i in range(length) : 
  
        # Update the position of 
        # the gold coin 
        if (string[i] == 'S') :
            total += 1; 
  
    # First player will win the game 
    if ((total % 2) == 1) :
        return "First"; 
    return "Second"; 
  
# Driver code 
if __name__ == "__main__" : 
  
    string = "GSSS"; 
    length = len(string); 
  
    print(getWinner(string, length)); 
      
# This code is contributed by kanugargng


输出:
First