in reply to 5x5 Puzzle

At first I had ignored this, then decided to do it. It was
a more fun challenge than I thought. There are, not
counting the order of the moves, actually 4 solutions in
15 moves for a 5x5 board. What follows is the throw-away
script I wrote to find this. By default it solves a 5x5
board. Pass it an argument and it will solve an nxn
board. (I tried it in the 1..10 range and found that there
is 1 solution for 1, 2, 3, 6, 7, 8 and 10. As I mentioned,
there are 4 for 5, plus 16 for 4 and 256 for 9. Don't ask
me why, I merely report what I found...)

It would not be hard to extend this to handle arbitrary rectangular boards. I also didn't need the globals but this is throw-away code and it was easier that way. I make no apologies for the huge numbers of anonymous functions. The fact that I can feasibly find all 64 solutions for an 11x11 board by brute-force search on my old laptop speaks loudly enough for the efficiency of the method...

use strict; use Carp; use vars qw($min $max @board @soln @toggles); $min = 1; $max = shift(@ARGV) || 5; @board = map [map 0, $min..$max], $min..$max; foreach my $x ($min..$max) { foreach my $y ($min..$max) { push @toggles, ["$x-$y", ret_toggle_square($x, $y)]; } } find_soln(); sub find_soln { if (! @toggles) { # Solved! print join " ", "Solution:", map $_->[0], @soln; print "\n"; } else { my $toggle = shift(@toggles); # Try with, then without if ($toggle->[1]->()) { push @soln, $toggle; find_soln(); pop @soln; } if ($toggle->[1]->()) { find_soln(); } unshift @toggles, $toggle; } } # Returns a function that switches one square and returns # true iff the new color is black sub ret_swap_square { my ($x, $y) = @_; #print "Generated with $x, $y\n"; my $s_ref = \($board[$x-1][$y-1]); return sub {$$s_ref = ($$s_ref + 1) %2;}; } # Returns a function that toggles one square and its # neighbours, and returns whether or not any neighbour # has turned to white and cannot return to black without # swapping again with $x lower or $x the same and $y lower. sub ret_toggle_square { my ($x, $y) = @_; my @fin_swaps; my @other_swaps; unless ($x == $min) { push @fin_swaps, ret_swap_square($x - 1, $y); } if ($x == $max) { unless ($y == $min) { push @fin_swaps, ret_swap_square($x, $y - 1); } if ($y == $max) { push @fin_swaps, ret_swap_square($x, $y); } else { push @other_swaps, ret_swap_square($x, $y); unless ($y == $max) { push @other_swaps, ret_swap_square($x, $y+1); } } } else { unless ($y == $min) { push @other_swaps, ret_swap_square($x, $y - 1); } push @other_swaps, ret_swap_square($x, $y); push @other_swaps, ret_swap_square($x + 1, $y); unless ($y == $max) { push @other_swaps, ret_swap_square($x, $y + 1); } } return sub { $_->() foreach @other_swaps; my $ret = 1; $ret *= $_->() foreach @fin_swaps; return $ret; } }

In Section
Cool Uses for Perl