Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Sum of N elements in an M element array

by tybalt89 (Monsignor)
on Feb 01, 2020 at 19:04 UTC ( [id://11112237]=note: print w/replies, xml ) Need Help??


in reply to Sum of N elements in an M element array

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11112217 use warnings; use List::Util qw( sum ); my @array = qw( 1 2 3 4 5 ); local $_ = "@array"; for my $possible ( 1 .. @array ) { my $pattern = join '.+?', ('\b(\d+)\b') x $possible; local $" = '+'; /$pattern(?{print "@{^CAPTURE} = ", sum(@{^CAPTURE}), "\n"})(*FAIL)/ +; }

Outputs:

1 = 1 2 = 2 3 = 3 4 = 4 5 = 5 1+2 = 3 1+3 = 4 1+4 = 5 1+5 = 6 2+3 = 5 2+4 = 6 2+5 = 7 3+4 = 7 3+5 = 8 4+5 = 9 1+2+3 = 6 1+2+4 = 7 1+2+5 = 8 1+3+4 = 8 1+3+5 = 9 1+4+5 = 10 2+3+4 = 9 2+3+5 = 10 2+4+5 = 11 3+4+5 = 12 1+2+3+4 = 10 1+2+3+5 = 11 1+2+4+5 = 12 1+3+4+5 = 13 2+3+4+5 = 14 1+2+3+4+5 = 15

Replies are listed 'Best First'.
Re^2: Sum of N elements in an M element array
by karlgoethebier (Abbot) on Feb 01, 2020 at 20:28 UTC

    I stared a little while at the code you provided wondering why and how it works and jumped to the conclusion that using Data::PowerSet is by far the better solution. Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

    perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help

      He's building a regex which is trying to match n numbers, because of the (fail) it keeps backtracking to match all possibilities.

      The embedded Perl code ensures the output before backtracking to the next match.

      I actual like seeing such code as answers to lazy questions. ;)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11112237]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2024-04-23 16:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found