Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m writing a tic-tac-toe game in C++ and now I found a function to check if a

ID: 659021 • Letter: I

Question

I'm writing a tic-tac-toe game in C++ and now I found a function to check if a player has a winning board for a connect four game.

The function looks like this:

bool haswon(int64_t board)
{
    int64_t y = board & (board >> 7);
    if (y & (y >> 2 * 7)) // check diagonal
        return true;
    y = board & (board >> 8);
    if (y & (y >> 2 * 8)) // check horizontal -
        return true;
    y = board & (board >> 9);
    if (y & (y >> 2 * 9)) // check / diagonal
        return true;
    y = board & (board >> 1);
    if (y & (y >> 2))     // check vertical |
        return true;
    return false;
}
I would be looking for an explanation of the above function.

Then I could perhaps try to implement the same thing for my tic-tac-toe. I'm fairly OK with the bitwise operators

#include <iostream>
#include <bitset>

namespace tictactoe {

    constexpr std::size_t N = 3;

    using board = std::bitset<N*N>;

    constexpr char NOUGHT = 'O';
    constexpr char CROSS = 'X';

    bool curr_move_noughts = true;

    board combined() {
        return noughts | crosses;    // combined bit board for both players
    }

}

Explanation / Answer

The pure fact you don't understand this function should be a big warning sign not to implement your Tic-Tac-Toe winning test in a similar manner. If you do, you will probably not understand your own code in a few weeks any more.

Instead, use a two-dimensional array or vector, and some loops to check the winning conditions. And don't think too much about speed or memory space as long as you don't experience any significant, measurable bottlenecks.