Advertisement
Guest User

Untitled

a guest
Mar 17th, 2016
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 1.38 KB | None | 0 0
  1. #!/usr/bin/env perl6
  2.  
  3. # perl6 stack_concurrent_2.p6  193,82s user 1,98s system 332% cpu 58,844 total
  4.  
  5. my @operators = <+ - * />;
  6. my Int @numbers = [12, 7, 3, 2, 48];
  7. my Int $solution = 15;
  8.  
  9. my @op = @operators;
  10. for 3..@numbers.elems {
  11.     @op = map { $_».list.flat.Array }, (@op X @operators);
  12. }
  13.  
  14. my @promises;
  15. for @numbers.permutations -> @list {
  16.     my $promise = start {
  17.         my @solutions;
  18.         for @op -> @possible-operator-list {
  19.             my @*stack;
  20.             my $*formula;
  21.             push-on-stack($_) for @list;
  22.             push-on-stack($_) for @possible-operator-list;
  23.             # with promise:
  24.             push @solutions, $*formula if @*stack[0] == $solution;
  25.             # without promise:
  26.             #say $*formula if @*stack[0] == $solution;
  27.         }
  28.         @solutions;
  29.     }.then(-> $p {say "found the solution with {$_}" for $p.result });
  30.     push @promises, $promise;
  31. }
  32.  
  33. await Promise.allof(@promises);
  34.  
  35. sub push-on-stack($item) {
  36.     #say "pushing $item on {@*stack.perl}";
  37.     $*formula ~= "$item ";
  38.     if $item ~~ Int {
  39.         @*stack.push($item);
  40.     }else{
  41.         @*stack.push(calc($item, @*stack.pop, @*stack.pop));
  42.     }
  43. }
  44.  
  45. sub calc(Str $op, $x, $y) {
  46.     given $op {
  47.         when '+' {return $x + $y}
  48.         when '-' {return $x - $y}
  49.         when '*' {return $x * $y}
  50.         when '/' {return $x / $y}
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement