Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env perl6
- # perl6 stack_concurrent_2.p6 193,82s user 1,98s system 332% cpu 58,844 total
- my @operators = <+ - * />;
- my Int @numbers = [12, 7, 3, 2, 48];
- my Int $solution = 15;
- my @op = @operators;
- for 3..@numbers.elems {
- @op = map { $_».list.flat.Array }, (@op X @operators);
- }
- my @promises;
- for @numbers.permutations -> @list {
- my $promise = start {
- my @solutions;
- for @op -> @possible-operator-list {
- my @*stack;
- my $*formula;
- push-on-stack($_) for @list;
- push-on-stack($_) for @possible-operator-list;
- # with promise:
- push @solutions, $*formula if @*stack[0] == $solution;
- # without promise:
- #say $*formula if @*stack[0] == $solution;
- }
- @solutions;
- }.then(-> $p {say "found the solution with {$_}" for $p.result });
- push @promises, $promise;
- }
- await Promise.allof(@promises);
- sub push-on-stack($item) {
- #say "pushing $item on {@*stack.perl}";
- $*formula ~= "$item ";
- if $item ~~ Int {
- @*stack.push($item);
- }else{
- @*stack.push(calc($item, @*stack.pop, @*stack.pop));
- }
- }
- sub calc(Str $op, $x, $y) {
- given $op {
- when '+' {return $x + $y}
- when '-' {return $x - $y}
- when '*' {return $x * $y}
- when '/' {return $x / $y}
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement