A different approach - here's my generic solution to find out who is the winner of the tic-tac-toe. The basic idea is to list out the winning patterns, and then automatically generate regular expressions based on these patterns. This solution assumes that there is only one winner in the game.
#!/usr/local/bin/perl -w
use strict;
use re 'eval';
# A list of all winning patterns, could generate them
# with some sort of algorithm, but it's easier just
# to type them out. ;-)
my @win = qw/
XXX......
X..X..X..
......XXX
..X..X..X
...XXX...
.X..X..X.
X...X...X
..X.X.X..
/;
foreach (@win) # dynamically generate regular expressions
{ # to look for matching winning patterns
my $c = 0;
s/X/!$c++?'([^-])':'(??{$1})'/ge;
}
while (my $game = <DATA>)
{
my $winner = 'No body';
foreach (@win) {
$winner = $1, last if $game =~ /$_/;
}
print "$winner wins\n";
}
__DATA__
XO-OX--OX
OX-XO--XO
OOXOXOXOO
OX-XOOXOX
And the output is -
X wins
O wins
X wins
No body wins
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.