Skip to content

Instantly share code, notes, and snippets.

@tobyink
Last active June 16, 2020 12:49
Show Gist options
  • Select an option

  • Save tobyink/3ee9b316d24ec522c7885bcbbece6481 to your computer and use it in GitHub Desktop.

Select an option

Save tobyink/3ee9b316d24ec522c7885bcbbece6481 to your computer and use it in GitHub Desktop.
Solution to a number puzzle in Perl
#!/usr/bin/env perl
use v5.12;
use strict;
use warnings;
use Algorithm::Permute;
sub main {
my $check = build_checker( \*DATA );
my $iterator = Algorithm::Permute->new( [ 1 .. 10 ] );
while ( my @list = $iterator->next ) {
if ( $check->( \@list ) ) {
say "Found: @list";
}
}
}
sub build_checker {
my ( $fh ) = @_;
# Checker code starts by unpacking arguments.
my $code = 'my ($A, $B, $C, $D, $E, $F, $G, $H, $I, $J) = @{ +shift };' . "\n";
# Read each line of restrictions.
while ( <$fh> ) {
chomp;
my ( $head, $letters ) = split /:/;
# Add restrictions to code being built.
for my $letter ( split //, $letters ) {
$code .= single_letter_check( $head, $letter ) . "\n";
}
}
# If none of the checks failed, test passed, so return true.
$code .= 'return !!1;';
# Compile check into coderef.
eval "sub { $code }";
}
sub single_letter_check {
sprintf( 'return if $%s == 1 + $%s;', @_ );
}
main();
__DATA__
A:BCDHJ
B:EGCAHD
C:ABDGHIJ
D:ACIHFB
E:BG
F:DI
G:EBCHJI
H:GBCDIJA
I:JHCDFG
J:GHICA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment