📌  相关文章
📜  找到将赢得硬币游戏的玩家

📅  最后修改于: 2021-09-24 03:18:27             🧑  作者: Mango

给定N 个硬币,任务是找到谁赢得硬币游戏。
硬币游戏是一种游戏,其中每个玩家从给定的N 个硬币中挑选硬币,这样他可以在一个回合中选择 1 到 5 个硬币的硬币,并且游戏对两个玩家都继续。选择最后一枚硬币的玩家输掉游戏。
例子:

Input: N = 4
Output: First Player
Explanation:
Player 1 pick 3 coins and 
Player 2 pick last coin

Input: N = 7
Output: Second Player

方法:

  • 由于玩家可以拿走 1 到 5 个硬币,如果玩家输了就意味着他只有 1 个硬币,否则他可能拿走的硬币比可用硬币少 1 个,并迫使另一个玩家输掉。所以现在我们将考虑第二个玩家要赢的情况,这意味着第一个玩家只有一个硬币。
  • 当N = 1时,第二个玩家将获胜,当N = 2到6时,第一个玩家可以选择比N少1个硬币,并迫使第二个玩家输掉所以丢弃它们,当N = 7时,第一个玩家可以选择硬币1到5,那会留下6到2的硬币,然后第二个玩家可以选择1到5,赢得第二个玩家会聪明地选择少1个硬币迫使先松,所以基本上从1开始,所有数字在 6 的差距上(无论第一个玩家选择什么,第二个玩家将选择等于 6 的硬币和第一个玩家选择的硬币)将是第二个玩家的胜利。
  • 最后,我们只需要检查 n 是否为 6*c+1 形式,如果它是第二个玩家将获胜,否则,第一个玩家将获胜。

下面是上述方法的实现:

C++
// C++ program to find the player
// who wins the game
 
#include 
using namespace std;
 
// Function to check the
// wining player
void findWinner(int n)
{
    // As discussed in the
    // above approach
    if ((n - 1) % 6 == 0) {
        cout << "Second Player wins the game";
    }
    else {
        cout << "First Player wins the game";
    }
}
 
// Driver function
int main()
{
 
    int n = 7;
    findWinner(n);
}


Java
// Java program to find the player
// who wins the game
class GFG
{
 
// Function to check the
// wining player
static void findWinner(int n)
{
    // As discussed in the
    // above approach
    if ((n - 1) % 6 == 0)
    {
        System.out.println("Second Player wins the game");
    }
    else
    {
        System.out.println("First Player wins the game");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 7;
    findWinner(n);
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program to find the player
# who wins the game
 
# Function to check the
# wining player
def findWinner(n):
     
    # As discussed in the
    # above approach
    if ((n - 1) % 6 == 0):
        print("Second Player wins the game");
    else:
        print("First Player wins the game");
     
# Driver Code
if __name__ == '__main__':
    n = 7;
    findWinner(n);
 
# This code is contributed by 29AjayKumar


C#
// C# program to find the player
// who wins the game
 
using System;
 
class GFG
{
     
    // Function to check the
    // wining player
    static void findWinner(int n)
    {
        // As discussed in the
        // above approach
        if ((n - 1) % 6 == 0)
        {
            Console.WriteLine("Second Player wins the game");
        }
        else
        {
            Console.WriteLine("First Player wins the game");
        }
    }
     
    // Driver Code
    public static void Main()
    {
        int n = 7;
        findWinner(n);
    }
}
 
// This code is contributed by AnkitRai01


Javascript


输出:

Second Player wins the game

时间复杂度: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程