barrachois has asked for the wisdom of the Perl Monks concerning the following question:
Our Tic Tac Toe board is a string of nine characters, "X", "O", or "-" for an empty space. Winning positions are a horizontal, vertical, or diagonal lines of three X's or O's. Code that tests a regex on the complete list of winning patterns and a few non-winning patterns is given below.^(...)*(X|O)\2\2|(X|O)(.{2,3}\3)\4|^..(X|O).\5.\5
The winning patterns all have three X's (or O's) followed by zero, one, two, or three dots. Somehow that makes me think that there may be a shorter regex than the one I've found.
- barrachois
1st Addendum and Correction :#!/usr/bin/perl -w # Test regular expression on Tic Tac Toe boards. my @X_wins = ( 'XXX......' , '...XXX...' , '......XXX' , 'X..X..X..' , '.X..X..X.' , '..X..X..X' , 'X...X...X' , '..X.X.X..' , ); my @O_wins = @X_wins; s/X/O/g for @O_wins; my @noone_wins = ( 'XO-------' , 'XX-XOO---' , '-XX-XX-O-' , 'OXO--XXO-' , 'OOXXXO---' , 'OXXX-XOO-' , 'OOXXX----' , 'XOOOXOOO-' , 'OXOXOX---' , ); foreach my $board (@X_wins, @O_wins, @noone_wins){ print "$board " . ( is_win($board) ? "is" : "is not") . " a win.\n"; } sub is_win { return shift =~ m/^(...)*(X|O)\2\2|(X|O)(.{2,3}\3)\4|^..(X|O).\5.\5/ +; }
Given Dave's suggestion of \w for X|O, the best I see so far is 57 characters.
2nd Addendum^(...)*(\w)\2\2|^..(\w).\3.\3|(\w)..\4..\4|(\w)...\5...\5
Thanks to all for the suggestions.(\w)(..(\1|.\1.)..\1|.\1.\1..$|\1\1(...)*$)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: tic-tac-toe regex golf
by davido (Cardinal) on Nov 18, 2003 at 06:10 UTC | |
|
Re: tic-tac-toe regex golf
by Roger (Parson) on Nov 18, 2003 at 06:40 UTC | |
|
Re: tic-tac-toe regex golf (bug)
by tye (Sage) on Nov 18, 2003 at 16:47 UTC | |
by barrachois (Pilgrim) on Nov 18, 2003 at 17:11 UTC | |
by Anonymous Monk on Nov 20, 2003 at 00:41 UTC | |
|
Re: tic-tac-toe regex golf
by Roy Johnson (Monsignor) on Nov 18, 2003 at 18:42 UTC | |
|
Re: tic-tac-toe regex golf
by Anonymous Monk on Dec 16, 2016 at 00:04 UTC |