I have this code to generate the anagrams for a 6 letters word:

letters = {"P", "E", "R", "I", "T", "O"};
perms = Permutations[letters, {6}];
list = StringJoin /@ perms;

Which gives me 720 possible combinations as expected. I'd like to select among those only the ones for which the vowels (i.e.: E, I and O) occur in alphabetical order. For instance:

"PERITO", "PERIOT" and "PERTIO" would be valid cases but "PERTOI", "PEROIT" and "PEROTI" would not. How can that be done?


4 Answers 4


Using StringMatchQ:

letters = {"P", "E", "R", "I", "T", "O"};
perms = Permutations[letters, {6}];
list = StringJoin /@ perms;

   StringExpression[___, "E", ___, "I", ___, "O", ___]]][list]

Same command with recognizable syntaxes:

 StringMatchQ[___ ~~ "E" ~~ ___ ~~ "I" ~~ ___ ~~ "O" ~~ ___]]

Select[StringMatchQ[___ ~~ "E" ~~ ___ ~~ "I" ~~ ___ ~~ 
    "O" ~~ ___]][list]

Using StringDelete:

vowels = {"E", "I", "O"};
StringDelete[Except[Alternatives @@ vowels]] /@ list // 
  Position["EIO"] // Extract[list, #] &


These are 120 in total.

letters = {"P", "E", "R", "I", "T", "O"};

perms = Permutations[letters, {6}];

Using Cases

Cases[perms, x : {___, "E", ___, "I", ___, "O", ___} :> StringJoin[x]]


letters = {"P", "E", "R", "I", "T", "O"};

perms = Permutations[letters, {6}];

Grabbing the @eldo's pattern and using ReplaceList:

patt = x : {___, "E", ___, "I", ___, "O", ___};

ReplaceList[perms, {___, patt, ___} :> StringJoin[x]]


Pick[#, StringMatchQ[RegularExpression[".*E.*I.*O.*"]] /@ #] &[list]


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.