Skip to content

Instantly share code, notes, and snippets.

@jacoby
Created October 9, 2015 14:39
Show Gist options
  • Select an option

  • Save jacoby/04ca296f588c5aa95a1f to your computer and use it in GitHub Desktop.

Select an option

Save jacoby/04ca296f588c5aa95a1f to your computer and use it in GitHub Desktop.
Solving my son's math homework with Recursion.
#!/usr/bin/env perl
use feature qw{ say state signatures } ;
use strict ;
use warnings ;
use utf8 ;
use Data::Dumper ;
my $numbers = [ 3 .. 11 ] ;
my $array ;
recurse_magic_box( $numbers, $array ) ;
sub recurse_magic_box ( $numbers , $array ) {
# numbers is the list of allowable numbers
for my $n (@$numbers) {
push @$array, $n ;
if ( check_magic_box($array) ) {
recurse_magic_box( $numbers, $array ) ;
}
pop @$array ;
}
}
sub check_magic_box ( $array ) {
for my $n (@$array) {
my $c = scalar grep {m{$n}} @$array ;
return 0 if $c > 1 ;
}
do {
my $sum = 21 ;
my $checks = [
[ 0, 1, 2 ], # first row
[ 3, 4, 5 ], # second row
[ 6, 7, 8 ], # third row
[ 0, 3, 6 ], # first col
[ 1, 4, 7 ], # second col
[ 2, 5, 8 ], # third col
[ 0, 4, 8 ], # diagonal from top right
[ 6, 4, 2 ], # diagonal from bottom right
] ;
for my $check (@$checks) {
my $s = 0 ;
for my $p (@$check) {
$s += $array->[$p] ;
}
return 0 if $s != $sum ;
}
say join "\t", @$array[ 0 .. 2 ] ;
say join "\t", @$array[ 3 .. 5 ] ;
say join "\t", @$array[ 6 .. 8 ] ;
say '' ;
} if scalar @$array == 9 ;
return 1 ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment