http://qs321.pair.com?node_id=1226058

QM has asked for the wisdom of the Perl Monks concerning the following question:

Today I learned that a regex can match permutations of a given string.

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