Perl-Sensitive Sunglasses PerlMonks

### Comment on

 Need Help??
On an evening some days ago when I was bored, I've challanged myself to solve something non-trivial by regexes. The resulting code follows, it is a solution to the 0-1 knapsack problem.
```use strict;
use warnings;
use re 'eval';
use List::Util 'sum';

my \$max_weight = 400;
my %items      = (      # value, weight: positive integers
'map'                    => { v => 150, w => 9 },
'compass'                => { v => 35,  w => 13 },
'water'                  => { v => 200, w => 153 },
'sandwich'               => { v => 160, w => 50 },
'glucose'                => { v => 60,  w => 15 },
'tin'                    => { v => 45,  w => 68 },
'banana'                 => { v => 60,  w => 27 },
'apple'                  => { v => 40,  w => 39 },
'cheese'                 => { v => 30,  w => 23 },
'beer'                   => { v => 10,  w => 52 },
'suntan_cream'           => { v => 70,  w => 11 },
'camera'                 => { v => 30,  w => 32 },
't_shirt'                => { v => 15,  w => 24 },
'trousers'               => { v => 10,  w => 48 },
'umbrella'               => { v => 40,  w => 73 },
'waterproof_trousers'    => { v => 70,  w => 42 },
'waterproof_overclothes' => { v => 75,  w => 43 },
'note_case'              => { v => 80,  w => 22 },
'sunglasses'             => { v => 20,  w => 7 },
'towel'                  => { v => 12,  w => 18 },
'socks'                  => { v => 50,  w => 4 },
'book'                   => { v => 10,  w => 30 },
);

my \$str = 'v' x sum( map \$_->{v}, values %items ) . '0' . 'w' x \$max_w
+eight;
#print \$str, "\n";

my \$i;
my \$left = my \$right = '';
for ( keys %items ) {
\$left .= sprintf "(?<%s>(?:%s)?)\n", \$_, 'v' x \$items{\$_}{v};
\$right .= sprintf "(?(?{ \\$%d })%s|)\n", ++\$i, 'w' x \$items{\$_}{w};
}

my \$re = sprintf "%s0\n(?=\n%s)\n", \$left, \$right;
#print \$re;

my \$sum = join '+', map length, grep length, \$str =~ /\$re/x;
print \$sum, '=', eval \$sum, "\n";
print join "\n", grep { length \$+{\$_} } keys %+; print "\n";

__END__

The input data came from rosettacode.org. With this input it runs for circa five minutes on my machine. If you want to play with it, just replace the input with something simpler, for instance:

```# a partition problem as a special case
my \$max_weight = 136;
my %items      = (
a => { w => 9, v => 9 },
b => { w => 12, v => 12 },
c => { w => 14, v => 14 },
d => { w => 17, v => 17 },
e => { w => 23, v => 23 },
f => { w => 32, v => 32 },
g => { w => 34, v => 34 },
h => { w => 40, v => 40 },
i => { w => 42, v => 42 },
j => { w => 49, v => 49 },
);

To understand what it does, just uncomment the print lines, supply it with some simple input, and see the contents of \$str and \$re for yourself. Probably you also want to replace the named captures with standard capturing parentheses in the \$left .= ... line as the naming is not essential, they're just there for the pretty printing of the output.

I'm still not fully satisfied with this solution, because the regex is not pure. (By saying pure I do not mean the compsci sense, but that it does not contain embedded code.) Anyway it's close to it, as the only non-pure part of it is something like this: (?(?{ \$1 })ww|). But I wasn't able to use (?(1)ww|) instead, because my captures are always matching, though sometimes matching the empty string.

For the educated monks there's probably nothing new in this since much of my inspiration came from Abigail's previous works:

Also there's much more on this topic in the monastery and elsewhere, however I haven't read them (yet):

If you've found bugs in the code above, please let me know.

Cheers,
rubasov

p.s. I've hesitated to post it to the Cool Uses for Perl section instead of Meditations, but all the similar posts were in Meditations so I posted here. Feel free to move it, if it fits better in the CUfP section.

In reply to knapsack problem solved by regex by rubasov

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
 [marto]: someone else writes: [http://www. evanmiller.org/why -im-learning-perl- 6.html|

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2017-07-26 13:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
I came, I saw, I ...

Results (395 votes). Check out past polls.