Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Sum to 100 at Rosetta Code

by trippledubs (Deacon)
on Feb 25, 2018 at 00:49 UTC ( [id://1209917]=note: print w/replies, xml ) Need Help??


in reply to Sum to 100 at Rosetta Code

For summing to 100, I got all but one with this

#!/usr/bin/env perl use strict; use warnings; use feature 'say'; my @queue = '123456789'; while (@queue) { $_ = shift @queue; say if eval == 100; while ( /\d+?/g) { next if (!$' || $' =~ /\+|\-/); push @queue,("$`$&+$'","$`$&-$'"); } }
123-45-67+89 123+4-5+67-89 123+45-67+8-9 1+2+34-5+67-8+9 1+23-4+5+6+78-9 1+23-4+56+7+8+9 12+3+4+5-6-7+89 12+3-4+5+67+8+9 12-3-4+5-6+7+89 123-4-5-6-7+8-9 1+2+3-4+5+6+78+9

Eventually resorted to this to get the last one

#!/usr/bin/env perl use strict; use warnings; use feature 'say'; my @queue = '123456789'; my %seen; while (@queue) { local $_ = shift @queue; next if (exists $seen{$_}); $seen{$_}++; say if eval == 100; while (/\d+?/g) { my ($pre,$match,$post) = ($`,$&,$'); push @queue, "$pre$match+$post" unless (!$post || $post =~ /[+ +-]/); push @queue, "$pre-$match$post" unless ($pre =~ /[-+]$/ ); } }

I think a better regex solution exists, this re-evaluates too many times. I used structure from tybalt89's Re: Parks Puzzle.

With '1234567891234' 1222 solutions

With '12345678912345' 3080 solutions

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-24 22:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found