Using Mathematica
and Maple
TM
391
This idea can be extended to patterns on a larger alphabet. For example,
the subsequence pattern 132 is coded as follows (where && denotes the logical
AND):
{___,x_,___,y_,___,z_,___}/; x < z && z<y
We use the function Position[list,pattern] to find where in a list of ob-
jects the pattern occurs. For example, if we want to find the subsequence
pattern 132 in the list {{1, 2, 3, 4}, {1, 4, 2, 3, 5}, {1, 5, 4}, {1, 1, 1, 1}} we use:
Position[{{1,2,3,4},{1,4,2,3,5},{1,5,4},{1,1,1,1}},
{___,x_,___,y_,___,z_,___} /; x < z && z < y]
which returns as answer the list
{{2},{3}}
This means that the pattern was detected in the second and third element of
the list. Since the result is a list, we can count the number of elements in the
list by using the function Length:
Length[{{2},{3}}]
which returns 2 as an answer. Thus two of the four entries of the original list
contained the subsequence pattern 132. Note that each word or composition
has to be expressed as a list, the the dominant structure in Mathematica.
However, the function used to create compositions renders them exactly in
this form. Now we can obtain the number of compositions that avoid a given
pattern by taking the total number of compositions and subtracting from it
the number of compositions that contain the pattern. For an example of
enumeration by direct pattern matching check out Example 5.14.
F.1.7 Random compositions
Mathematica has several built-in functions that are useful for creating ran-
dom compositions and computing probabilities. To select an element at
random from a list of values or list of compositions, use RandomChoice.
RandomChoice[vals,n] gives a list of n pseudorandom choices from the list
vals. Note that each value is equally likely to be chosen and a value can be
chosen more than once. For example, to obtain 10 random compositions of
n =5,weuse
comps[n_] := Flatten[Map[Permutations,IntegerPartitions[n]],1]
RandomChoice[comps[5],10]
which produces an answer similar to {{3, 2}, {3, 1, 1}, {2, 1, 1, 1}, {2, 1, 1, 1},
{2, 1, 2}, {1, 2, 1, 1}, { 3, 1, 1}, {3, 1, 1}, {1, 2, 2}, { 1, 1, 2, 1}}.Eachtimethis
command is executed, a different answer will result.
Mathematica has also many functions relating to discrete and continuous
random variables. Probability mass functions and density functions are com-
puted using PDF[dist,x]. To see a list of all the built-in distributions, use
© 2010 by Taylor and Francis Group, LLC