For those who don’t know what Pentago is, it’s not really that important to the problem, but suffice to say that you have a 6×6 board with four quadrants. Each player takes turns placing a piece and then rotating a quadrant. The game is won when one player gets five in a row (either before or after the player’s rotate phase).
I’m writing an algorithm to play many different random Pentago games. However, since it’s completely random, I see no good way to get around checking to see if someone wins in between the place and rotate phase of the turn (otherwise, you might accidentally rotate the winning move). Eventually, I plan on rewriting this to where it has a little bit more strategy involved instead of completely random, but this is for statistical purposes, so randomness does just fine (and in fact is quite useful in some ways).
Anyways, currently I am programming in Matlab, and an empty board looks like this
eeeeee
eeeeee
eeeeee
eeeeee
eeeeee
eeeeee
As the game progresses, the board fills with w‘s and b‘s. The way that I check for a winning board is quite literally iterating through every column and every row (and every diagonal) to see if there is a winner by performing a regular expression check on the “string” that is returned.
In short, my question is this:
Is there a more efficient method for determining the winners of a Pentago board?
EDIT:
There are two solutions I’ve come up with: one based on convolution (using the function CONV2) and one based on brute-force indexing for all possible strings of 5 elements (similar to b3’s newer answer). Here they are:
Convolution:
Indexing:
Out of curiosity, I thought I’d measure the speed and accuracy of these solutions versus b3’s newer answer. I created 4 test boards: -1 wins, no winner, 1 wins, both win (draw). Then I ran each solution 10,000 times for each board and timed them. Here are the results:
Note that b3’s solution fails to detect a draw. Even though the code for the convolution-based solution was the shortest and easiest to implement (I didn’t have to create a list of indices by hand), the indexing solution I give above ends up being the fastest.