Efficient algorithm for counting unique states of tic tac toe

后端 未结 6 844
抹茶落季
抹茶落季 2021-02-07 12:51

I\'m trying to build a tic tac toe game to demonstrate and experiment with machine learning algorithms, and i\'ve found an interesting problem.

eg: a tic tac toe board c

6条回答
  •  礼貌的吻别
    2021-02-07 13:11

    Combining some of the ideas from the other answers...

    Do not map configurations to numbers. Use numbers to represent configurations. Write methods to operate on the representation if you really need to get/set by x,y location.

    Then choose a representation that you can operate on efficiently to answer the question. Here is one idea.

    You have three operations, so let's give them names:

    • R = rotate board 90 degrees counter-clockwise
    • M = mirror board about y-axis
    • I = invert board (what you call "juxtapose", but I think "invert" is more descriptive)

    You want to count the number of equivalence classes of boards under the orbit of these operations. There are at most 16 elements in each equivalence class. Given a board, you can generate the other 15 equivalent boards by applying the operations in the following sequence:

    R, R, R, I, R, R, R, M, R, R, R, I, R, R, R

    (There are other sequences that work, too...)

    So a good idea would be to pick a representation that makes R fast, I somewhat fast, and not worry too much about M.

    Since R does not change the center, I would hold that somewhere else, and use a sequence of 2-bit numbers to represent the other 8 squares. I would let the first 2-bit number represent the lower-left, the next 2-bit number represent the square next to that, and so on, moving counter-clockwise around the board. I would let 00 represent "O", 11 represent "X", and both 01 and 10 represent "empty" (because then operation I becomes a simple flipping of bits).

    Then if you write those 8 2-bit numbers as a single 16-bit number, operation R is just a rotate operation on the 16-bit number, which your CPU can probably perform in a single instruction. Operation I is just XOR with -1 (but do not forget to invert the center square too). Operation M is a complicated bunch of bit-munging, but since you only do it one time out of 15, who cares?

    This should let you take any representation and quickly generate the other 15 that are equivalent. Then as Dialecticus suggests, pick the numerically smallest representation as your canonical member of the equivalence class and count those.

提交回复
热议问题