in reply to Checking Tic-Tac-Toe Win conditions?

If you take each 3x3 game grid and flatten it to a string of nine characters, this can be solved with a regexp. This particular method of solving it wasn't really touched upon in (Golf) Tic Tac Toe, but works great. The conversion of a 3x3 grid to a single flat string is trivial, so I'll just demonstrate the regexp portion of the solution.

The regexp can be expressed in a way that tests for one of four conditions. I started out with a slightly more complex regexp, and then was able to see the forest through the trees, and found a way to boil it down to this common denominator.

In the following snippet, I never placed any 'o's because I wanted to keep it visually clear what was going on. The hyphens could be replaced with x's and o's as though a real game were being played, and the regexp will discover whether X or O wins. I just wanted to show each of the winning possibilities, so I used hyphens to isolate X.

Here's the code:

use strict; use warnings; # Assume that the 3x3 AoA has been flattened to a single string. # Each string, therefore, equates to a single game. my @games = ( "x---x---x", # Diag from top left. 1 "--x-x-x--", # Diag from top right. 3 "x--x--x--", # Vert from top left. 2 "xxx------", # Horiz from top left. 4 "---xxx---", # Horiz from mid left. 4 "------xxx", # Horiz from bottom left. 4 "-x--x--x-", # Vert from top mid. 2 "--x--x--x" ); my $i; foreach my $game ( @games ) { print "Game ", ++$i, "\t"; if ( $game =~ m/ ([xo]) (?: (?:...\1){2} | (?:..\1){2} | (?:.\1){2} | \1{2}(?=(?:...){0,2}$) ) /ix ){ print "$1 wins.\n"; } else { print "no winner\n"; } }

Update:
Here's a golfier version that uses the same solution technique:

print m/([xo])((...\1){2}|(..\1){2}|(.\1){2}|\1{2}(?=(...){0,2}$))/i? "$1 wins.\n":"No winner.\n" foreach qw/x---x---x --x-x-x-- x--x--x-- xxx------ ---xxx--- ------xxx -x--x--x- --x--x--x x---x-x--/;

Update2: Fixed a problem that would allow misaligned 3-in-a-rows to win when they shouldn't.


Dave