Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Perl solution to the Vietnamese pesky snake
#!/usr/bin/perl
#
# Solution to the Vietnamese pesky snake in perl :)
# Calculates all 128 solutions
# http://www.theguardian.com/science/alexs-adventures-in-numberland/2015/may/21/how-to-solve-the-maths-puzzle-for-vietnamese-eight-year-olds-that-stumped-parents-and-teachers
#
# function: a+(13*b/c) + d + (12*e) - f - 11 + (g*h/i)-10;
# Setup the numbers to insert
@a = qw(1 2 3 4 5 6 7 8 9);
# For counting solutions
$count = 0;
# Start permutating
&perm(0);
# Using easy backtracking
sub perm {
my ($k) = @_;
my $len = $#a+1;
if ($k==($#a+1)) {
my $sum = $a[0]+(13*$a[1]/$a[2])+$a[3]+(12*$a[4])-$a[5]-11+($a[6]*$a[7]/$a[8])-10;
if ($sum==66) {
print ++$count.": ";
for my $i (0..$#a) {
print $a[$i]." ";
}
print "\n";
}
} else {
for (my $i=$k; $i<=$#a;$i++) {
my $t = $a[$k];
$a[$k] = $a[$i];
$a[$i] = $t;
&perm($k+1);
$t = $a[$k];
$a[$k] = $a[$i];
$a[$i] = $t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.