Last active
April 20, 2021 00:59
-
-
Save nicomen/0346678b375aecdd0bba32da13260c12 to your computer and use it in GitHub Desktop.
1 out of 10 cats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use feature 'say'; | |
use Algorithm::Combinatorics qw(variations_with_repetition permutations); | |
use List::SomeUtils qw/zip natatime/; | |
my $nums = [qw{75 25 5 8 10 9}]; | |
my $ops = [qw{+ - / *}]; | |
my $sum = 119; | |
my @answers = (); | |
# get all permutation of numbers | |
my $p_iter = permutations($nums); | |
while (my $p = $p_iter->next) { | |
# combine with all combinations of operators in between numbers | |
# second argument is amount of spaces between numbers to fill in with operators | |
my $v_iter = variations_with_repetition($ops, scalar(@{$p}) - 1); | |
while (my $v = $v_iter->next) { | |
# mix numbers and operators together | |
my $expr = join ' ', grep { defined } zip(@{$p}, @{$v}); | |
# execute resulting expression | |
my $res = eval $expr; | |
# store answer if matched sum | |
push(@answers, $expr) if $res == $sum; | |
} | |
} | |
# print results | |
say "There are " . scalar(@answers) . " combinations that give $sum:"; | |
# divide into columns to get a more quadratic output suitable for screenshot | |
my $iter = natatime 6, @answers; | |
while (my @cols = $iter->()) { | |
say join " ", map { "$_ = $sum" } @cols; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment