Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

For example, I might want to generate all length n=6 words on the alphabet {A, B, C} that have one A, three B's and two C's. An example of such a word is: 'ABBBCC'. I'd like to generate all such words.

I've already tried generating all permutations of a particular string (like 'ABBBCC') and deleting all duplicates. This is too slow for my purposes.

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

Permutations is already duplicate-aware:

Permutations[{"A", "A", "B"}]
{{"A", "A", "B"}, {"A", "B", "A"}, {"B", "A", "A"}}

Perhaps you are looking for combinations of a particular length (which can then be permuted). One way to get those is this:

f[k_, {}, c__] := If[+c == k, {{c}}, {}]

f[k_, {x_, r___}, c___] := Join @@ (f[k, {r}, c, #] & /@ 0~Range~Min[x, k - +c])

Use:

f[4, {1, 3, 2}]
{{0, 2, 2}, {0, 3, 1}, {1, 1, 2}, {1, 2, 1}, {1, 3, 0}}

These represent the words of length 4 for a list with unique items repeated, 1, 3, and 2 times at most.

You can then construct the actual words from these lists, e.g.:

char = {"A", "B", "C"};

StringJoin@MapThread[ConstantArray, {char, #}] & /@ f[4, {1, 3, 2}]
{"BBCC", "BBBC", "ABCC", "ABBC", "ABBB"}

Of course if you want the permutations you would permute before StringJoin.

share|improve this answer
    
Sigh. I didn't bother to look at the documentation for permutations because I assumed it wasn't. Thank you! –  rjkaplan May 3 '12 at 0:42
1  
Could you please avoid (or stop) the use of quote block for output? I find the thin grey bar on yellow BG highly distracting and really, serves no purpose. I think enclosing it in (* *) is cleaner and since it's shown in subtle grey, it's not too distracting either... –  rm -rf May 3 '12 at 0:44
    
Your first answer was sufficient. Thank you :D –  rjkaplan May 3 '12 at 0:44
5  
@R.M I don't really know what to say; I much prefer this format. I seem to recall this was on Meta; I'll look for the popular opinion. –  Mr.Wizard May 3 '12 at 0:48
4  
@R.M besides not very copyable I don't have much problems with this style. I find it visually more clear and attractive than the one I proposed myself in the Meta. It mimics one of mma's own styles. –  Sjoerd C. de Vries May 3 '12 at 6:54
show 5 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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