QM has asked for the wisdom of the Perl Monks concerning the following question:
Update: Oops, I had the terms reversed on the regex, it should be $i =~ $x .... I've corrected it, but it doesn't really change the results.
For single characters without repeats, such as any permutation of 'abc', this seems the shortest, most readable method:
@x = glob('{a,b,c}'x3); # for testing: all permutations, plus many mor +e $x = '(?:([a-c])(?!.*\1)){3}'; # regex for $i (@x) { $i =~ $x and say $i; # was $x =~ $i }
which outputs:
abc acb bac bca cab cba
For single character, with limited repeats, such as any permutation of 'aabbcc', a slightly different approach is needed. I tried the following, but it matches almost everything. I suspect there's some unexpected behavior in the backtracking?
@x = glob('{a,b,c}'x6); $x = '(?:a()|a()|b()|b()|c()|c()){6}\1\2\3\4\5\6'; # limited repeats a +llowed for $i (@x) { $i =~ $x and say $i; # was $x =~ $i }
which outputs 540 of the 728 strings given (at least 1 of each char is present):
aaaabc aaaacb aaabac aaabbc aaabca ... cccbba cccbca ccccab ccccba
Is there some other magic to DWIM?
For nonrepeating, multichar permutations, even when individual chars are shared between tokens, this approach works:
@x = glob('{abc,bcd,cde}'x3); # permutations of 'abc/bcd/cde' $x = '(?:abc()|bcd()|cde()){3}\1\2\3'; for $i (@x) { $i =~ $x and say $i; # was $x =~ $i }
which outputs:
abcbcdcde abccdebcd bcdabccde bcdcdeabc cdeabcbcd cdebcdabc
I found this here on Stack Overflow.
-QM
--
Quantum Mechanics: The dreams stuff is made of
-QM
--
Quantum Mechanics: The dreams stuff is made of
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Matching permutations with regex
by Eily (Monsignor) on Nov 20, 2018 at 14:01 UTC | |
by QM (Parson) on Nov 22, 2018 at 09:27 UTC | |
Re: Matching permutations with regex
by tybalt89 (Monsignor) on Nov 20, 2018 at 12:51 UTC | |
by QM (Parson) on Nov 22, 2018 at 09:20 UTC | |
by tybalt89 (Monsignor) on Nov 22, 2018 at 15:52 UTC | |
Re: Matching permutations with regex
by tybalt89 (Monsignor) on Nov 20, 2018 at 15:22 UTC | |
Re: Matching permutations with regex
by rsFalse (Chaplain) on Nov 21, 2018 at 14:10 UTC | |
by QM (Parson) on Nov 22, 2018 at 09:32 UTC |