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

Modified Game of Nim: เกม님을แบบปรับเปลี่ยนในภาษา C

เกม Nim แบบปรับเปลี่ยน: มีอาร์เรย์ตัวเลข Player 1 ลบตัวเลขที่หาร 3 ลงตัว, Player 2 ลบตัวเลขที่หาร 5 ลงตัว ใครไม่มีตัวเลขให้ลบก่อนแพ้

ตัวอย่าง

Array: {1, 5, 75, 2, 65, 7, 25, 6}

A ลบ 75 → B ลบ 5 → A ลบ 6 → B ลบ 65 → A ไม่มีตัวลบ → B ชนะ

ตรรกะ

  • นับ movesA = จำนวนหาร 3 ลงตัวอย่างเดียว
  • movesB = จำนวนหาร 5 ลงตัวอย่างเดียว
  • movesBoth = จำนวนหารทั้ง 3 และ 5 ลงตัว (LCM = 15)
  • ถ้า movesBoth == 0: ใครมี moves มากกว่าชนะ
  • ถ้ามี movesBoth: A เริ่มก่อน จึงได้เปรียบ 1 ตัว → ถ้า movesA + 1 > movesB A ชนะ

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

#include <bits/stdc++.h>
using namespace std;

int main() {
    int arr[] = {1, 5, 75, 2, 65, 7, 25, 6};
    int n = sizeof(arr) / sizeof(arr[0]);
    int movesA = 0, movesB = 0, movesBoth = 0;
    
    for (int i = 0; i < n; i++) {
        if (arr[i] % 3 == 0 && arr[i] % 5 == 0) movesBoth++;
        else if (arr[i] % 3 == 0) movesA++;
        else if (arr[i] % 5 == 0) movesB++;
    }
    
    if (movesBoth == 0) {
        if (movesA > movesB) cout << "Player 1 wins";
        else cout << "Player 2 wins";
    } else {
        if (movesA + 1 > movesB) cout << "Player 1 wins";
        else cout << "Player 2 wins";
    }
    return 0;
}

ผลลัพธ์

Player 2 is the Winner