2020 Jan Gold Problem 3 Springboards

From Wiki
Jump to navigation Jump to search

Official Problem Statement[edit]

Springboards

Problem Statement[edit]

Springboards is a game played on an N×N board. The board is initially empty. There are two players, Alice and Bob. In each turn, a player places one of their pieces on an empty cell of the board. The game ends when all cells of the board are filled.

The player who has the most pieces in a row, column, or diagonal wins the game. If both players have the same number of pieces in a row, column, or diagonal, the game is a draw.

Solution[edit]

The solution to this problem is to use a two-dimensional array to represent the board. We can use a loop to iterate through the board and check for any rows, columns, or diagonals that have the same number of pieces for both players. If one player has more pieces in a row, column, or diagonal, they are declared the winner. Otherwise, the game is a draw.

The following C++ code implements this solution:

#include <iostream>

const int N = 8;

int board[N][N];

int checkWin() {
    int aliceCount, bobCount;
    // Check rows
    for (int i = 0; i < N; i++) {
        aliceCount = 0;
        bobCount = 0;
        for (int j = 0; j < N; j++) {
            if (board[i][j] == 1) aliceCount++;
            else if (board[i][j] == 2) bobCount++;
        }
        if (aliceCount > bobCount) return 1;
        else if (bobCount > aliceCount) return 2;
    }
    
    // Check columns
    for (int j = 0; j < N; j++) {
        aliceCount = 0;
        bobCount = 0;
        for (int i = 0; i < N; i++) {
            if (board[i][j] == 1) aliceCount++;
            else if (board[i][j] == 2) bobCount++;
        }
        if (aliceCount > bobCount) return 1;
        else if (bobCount > aliceCount) return 2;
    }
    
    // Check diagonals
    aliceCount = 0;
    bobCount = 0;
    for (int i = 0; i < N; i++) {
        if (board[i][i] == 1) aliceCount++;
        else if (board[i][i] == 2) bobCount++;
    }
    if (aliceCount > bobCount) return 1;
    else if (bobCount > aliceCount) return 2;
    
    aliceCount = 0;
    bobCount = 0;
    for (int i = 0; i < N; i++) {
        if (board[i][N-i-1] == 1) aliceCount++;
        else if (board[i][N-i-1] == 2) bobCount++;
    }
    if (aliceCount > bobCount) return 1;
    else if (bobCount > aliceCount) return 2;
    
    return 0;
}

int main() {
    // Initialize board
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            board[i][j] = 0;
        }
    }
    
    // Play game
    while (true) {
        // Alice's turn
        // ...
        
        // Bob's turn
        // ...
        
        // Check for win
        int winner = checkWin();
        if (winner == 1) {
            std::cout << "Alice wins!" << std::endl;
            break;
        } else if (winner == 2) {
            std::cout << "Bob wins!" << std::endl;
            break;
        }
    }
    
    return 0;
}