Skip to content

Instantly share code, notes, and snippets.

@timo
Created October 22, 2015 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timo/41ecb85a9fad659f6809 to your computer and use it in GitHub Desktop.
Save timo/41ecb85a9fad659f6809 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl6
my int $checks = 0;
my int $limit = 100_000;
my @numbers = 3 .. 11 ;
my @array ;
recurse_magic_box( @numbers, @array ) ;
sub recurse_magic_box ( @numbers , @array ) {
my $set = set(@array);
for @numbers -> int $n {
unless $set{$n} {
@array.push($n);
if @array < 9 or check_magic_box( @array ) {
recurse_magic_box( @numbers, @array ) ;
}
@array.pop ;
}
}
}
=for optimizations
this little piece should be at least as fast as the recursion strategy,
but isn't. it's Probably just .permutations that wants to get the "GLR"
treatment.
#for (flat 3..11).permutations -> $array {
#check_magic_box($array);
#}
sub check_magic_box ( @array ) {
#return 0 if @array > 9 ;
#return 0 if (set @array) != @array;
#say "check $checks magic box for @array[]";
exit if $checks++ == $limit;
#if ( @array.elems == 9 ) {
# say @array ;
my $sum = 21 ;
return 0 if $sum != @array[0] + @array[1] + @array[2] ;
return 0 if $sum != @array[3] + @array[4] + @array[5] ;
return 0 if $sum != @array[6] + @array[7] + @array[8] ;
return 0 if $sum != @array[0] + @array[3] + @array[6] ;
return 0 if $sum != @array[1] + @array[4] + @array[7] ;
return 0 if $sum != @array[2] + @array[5] + @array[8] ;
return 0 if $sum != @array[0] + @array[4] + @array[8] ;
return 0 if $sum != @array[6] + @array[4] + @array[2] ;
say @array[ 0 .. 2 ] ;
say @array[ 3 .. 5 ] ;
say @array[ 6 .. 8 ] ;
say '' ;
#}
1;
}
# real 104m3.203s
# user 93m25.498s
# sys 0m10.577s
# I think I'm doing something wrong, because this shouldn't take that long, but I don't know what.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment