|
|
| go ahead... be a heretic | |
| PerlMonks |
tic-tac-toe regex golfby barrachois (Pilgrim) |
| on Nov 18, 2003 at 01:03 UTC ( [id://307918]=perlquestion: print w/replies, xml ) | Need Help?? |
This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.barrachois has asked for the wisdom of the Perl Monks concerning the following question:
I have a question from a friend on finding the
shortest regular expression that will identify a winning
position in Tic Tac Toe. So for those of you who like
perl golf (fewest keystrokes wins), I'd appreciate hearing
if you see ways to do this in a shorter regex than I've
found, which is 49 characters:
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. 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 : My 49 character regex is incorrect; it fails to see that 'XO--X-O-X' is a win. The part of my original regex which was supposed to see this as a winning string is /(X|O)(.{2,3}\1)\2/ which is supposed to be match three X's with two or three arbitrary chars between them. However, using the match \2 requires that the intervening charcters be the same. Oops. So I guess I need to list those two cases explicitly. Given Dave's suggestion of \w for X|O, the best I see so far is 57 characters.
2nd Addendum The shortest as of Nov 19, contributed anonymously, is this 43 character solution. Very nice. Thanks to all for the suggestions.
Back to
Seekers of Perl Wisdom
|
|
||||||||||||||||||||||||||||||||||||||||