Next | Program Repair Shop | 172 |
A table-driven approach is simpler than complicated logic
The code to generate the table might be complicated
But it will not be more complicated than the original logic!
If the table is small, you can hard-code it:
my @table = ( [ 0,0 , 0,1 , 0,2 ], [ 1,0 , 1,1 , 1,2 ], [ 2,0 , 2,1 , 2,2 ], [ 0,0 , 1,0 , 2,0 ], [ 0,1 , 1,1 , 2,1 ], [ 0,2 , 1,2 , 2,2 ], [ 0,0 , 1,1 , 2,2 ], [ 0,2 , 1,1 , 2,0 ], );
for my $win (@table) { my ($x1, $y1, $x2, $y2, $x3, $y3) = @$win; if ($board->[$x1][$y1] eq $board->[$x2][$y2] && $board->[$x1][$y1] eq $board->[$x3][$y3]) { return $board->[$x1][$y1]; } }
Result: 5 lines of code, and a table
We can fix a looming bug by changing the innermost line:
return $board->[$x1][$y1] if $board->[$x1][$y1];
Next | Copyright © 2002 M. J. Dominus |