Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Game of Nim: ทายผู้ชนะเมื่อเอาหินทีละ 1 ก้อนใน C++

ในเกม Nim นี้ เรามีกองหิน N ก้อน และผู้เล่น 2 คน (Player A และ Player B) สลับกันเอาหินทีละ 1 ก้อน Player A เริ่มก่อน คนที่เอาหินก้อนสุดท้ายชนะ

ตัวอย่างเพื่อเข้าใจปัญหา

Input: N = 6 Output: playerB

ลำดับ: A-B-A-B-A-B → B เอาก้อนสุดท้าย

วิธีการแก้ปัญหา

สังเกตรูปแบบ:

  • N = 1 → A ชนะ
  • N = 2 → B ชนะ
  • N = 3 → A ชนะ
  • N = 4 → B ชนะ

สรุป: N คี่ → Player A ชนะ, N คู่ → Player B ชนะ

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

bool findGameofNimWinner(int N) {
    return (N % 2 != 0); // true = A, false = B
}

int main() {
    int N = 26;
    cout << "The winner of the Game of Nim is ";
    findGameofNimWinner(N) ? cout << "Player A" : cout << "Player B";
    return 0;
}

ผลลัพธ์

The winner of the Game of Nim is Player B