Word break problem: Difference between revisions

Content deleted Content added
Trizen (talk | contribs)
Added Sidef
SqrtNegInf (talk | contribs)
m →‎{{header|Perl}}: updated output, simplified regex
Line 500: Line 500:


=={{header|Perl}}==
=={{header|Perl}}==
Look for words in alternation <code>$one_of</code>, but don't allow repeats (<code>?!\1</code> for the 1st, <code>?!\2</code> for the 2nd, etc). Easily extended by adding more terms to the pattern.
<lang perl>use strict;
<lang perl>use strict;
use warnings;
use warnings;


my @words = <a o is pi ion par per sip miss able>;
my @words = <a o is pi ion par per sip miss able>;
print "$_: " . word_break($_,@words) . "\n" for <a aa amiss parable opera operable inoperable permission mississippi>;

print "$_: " . word_break($_,@words) . "\n" for <a amiss parable opera operable inoperable permission mississippi>;


sub word_break {
sub word_break {
Line 512: Line 510:
my @matches;
my @matches;
my $one_of = join '|', @dictionary;
my $one_of = join '|', @dictionary;
@matches = $word =~ /^ ($one_of)(?!\1) (?:($one_of)(?!\2))? (?:($one_of)(?!\3))? (?:($one_of)(?!\4))? $/x;
@matches = $word =~ /^ ($one_of) ($one_of)? ($one_of)? ($one_of)? $/x # sub-optimal: limited number of matches
return join(' ', grep {$_} @matches) || "(not possible)";
return join(' ', grep {$_} @matches) || "(not possible)";
}</lang>
}</lang>
{{out}}
{{out}}
<pre>a: a
<pre>a: a
aa: a a
ado: ad o
amiss: a miss
amiss: a miss
admission: ad miss ion
parable: par able
parable: par able
opera: o per a
opera: o per a
operable: o per able
operable: o per able
inoperable: (not possible)
inoperable: in o per able
permission: per miss ion
permission: per miss ion
permissible: Not possible
mississippi: miss is sip pi</pre>
mississippi: miss is sip pi</pre>