Skip to content

Instantly share code, notes, and snippets.

Created December 22, 2012 16:03
Show Gist options
  • Save anonymous/4359618 to your computer and use it in GitHub Desktop.
Save anonymous/4359618 to your computer and use it in GitHub Desktop.
Solution to the logic puzzle
use v6;
my $limit = 100;
# before they talk any X*Y where 1<X<Y<X+Y<$limit is allowed as p
my %products;
for 2 .. $limit -> $X {
for $X+1 .. $limit-$X -> $Y {
%products{$X * $Y}++;
}
}
# when P says "I don't know", only products with %products{$p} > 1
# are allowed
my %sums_with_ambiguous_products;
for 2 .. $limit -> $X {
for $X ^.. $limit - $X -> $Y {
if %products{ $X * $Y } == 1 {
%sums_with_ambiguous_products{ $X + $Y } = 1;
}
}
}
# when S says "I don't know", only sums that are not in
# %sums_with_ambiguous_products are allowed
my %products_that_cause_S_not_to_know;
for 2 .. $limit -> $s {
if !%sums_with_ambiguous_products{$s} {
for 2 .. $s/2 + 1 -> $X {
my $p = $X * ($s - $X);
if (%products{$p} // 0) > 1 {
%products_that_cause_S_not_to_know{$p}++;
}
}
}
}
# only the products that can by split into two pairs (X,Y), where X+Y is
# allowed in only one way, are allowed. i.e.,
# %products_that_cause_S_not_to_know{$p} == 1
my %unambiguous_sums;
for 2 .. $limit -> $s {
next if %sums_with_ambiguous_products{$s};
for 2 .. $s / 2 + 1 -> $X {
my $p = $X * ($s - $X);
if (%products_that_cause_S_not_to_know{$p} // 0) == 1 {
%unambiguous_sums{$s}++;
}
}
}
for %unambiguous_sums.keys -> $s {
next unless %unambiguous_sums{$s} == 1;
for 2 .. $s / 2 + 1 -> $X {
my $Y = ($s - $X);
my $p = $X * ($s - $X);
if %products_that_cause_S_not_to_know{$p} == 1 {
say "(S, P) = ($s, $p), (X, Y) = ($X, $Y)";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment