Generate a list of all unique Tic Tac Toe boards

前端 未结 7 2073

I would like to generate a text file containing all 19,683 Tic-Tac-Toe board layouts in the structure of 0 = Blank, 1 = X, and 2 = O. Unfortunately math is not my strong su

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-30 09:42

    You can simply brute force your way through. Each of the squares is 0, 1 or 2 so...:

    for (int i1 = 0; i1 <= 2; i++) {
        for (int i2 = 0; i2 <= 2; i++) {
            // ...
            // lot's of nested for loops
            // ...
        }
    }
    

    Or, if you can't be bothered with that ;) then you can write a recursive function for it:

    int square[9];
    void place(int square_num) {
        if (square_num == 9) {
            output the current configuration
        }
    
        for (int i = 0; i <= 2; i++) {
            square[square_num] = i;
            place(square_num+1);
        }
    }
    

    Then just do:

    place(0);
    

    and magic will occur.

    This is in c++ by the way.

提交回复
热议问题