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.

I'm looking for an elegant way of doing a probability weighted replacement rule,

something like this

f[x_] :=  x /.  {1,2,3,4} -> {50%{ 4,3,2,1} ,50%{1,3,2,4}}

Using an If statement and generating a RandomReal will be very clumsy as I want different probabilities depending on the pattern I want replaced.

Thanks

share|improve this question

2 Answers 2

up vote 9 down vote accepted

You can use RandomChoice to randomly select an item from a list.

You can even randomly select an operator and apply it. For example:

f[x_List] := RandomChoice[{Reverse, Identity}][x]

Table[f[{1, 2, 3, 4}], {10}]

returns:

{{4, 3, 2, 1}, {4, 3, 2, 1}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 
  4}, {1, 2, 3, 4}, {4, 3, 2, 1}, {1, 2, 3, 4}, {4, 3, 2, 1}, {1, 2, 
  3, 4}}

As pointed by @WReach you can also assign a weight to each choice (weights are automatically normalized, i.e. they not need to sum to 1). For example:

f[x_List] := RandomChoice[{3, 1} -> {Reverse, Identity}][x]
Table[f[{1, 2, 3, 4}], {10}]

returns:

{{4, 3, 2, 1}, {4, 3, 2, 1}, {4, 3, 2, 1}, {4, 3, 2, 1}, {4, 3, 2, 
  1}, {1, 2, 3, 4}, {4, 3, 2, 1}, {1, 2, 3, 4}, {4, 3, 2, 1}, {1, 2, 
  3, 4}}

Your specific pseudo-code can be replaced with something like:

f[x_] := x /. {1, 2, 3, 4} :> RandomChoice[{{1, 2, 3, 4}, {4, 3, 2, 1}}]
Table[f[{1, 2, 3, 4}], {10}]
share|improve this answer

Another option is to use Condition:

Replace[foo, {foo_ /; RandomReal[] < p :> bar, foo_ :> baz}]

where p is the probability you want to give to the first replacement.

This is somewhat similar to using an If, but I find it somewhat more idiomatic. I would also avoid using ReplaceAll, when you actually want Replace as ReplaceAll might recurse down the whole expression.

You could also explore random function definition:

ff[x_] /; RandomReal[] < p := bar
ff[x_] := baz

Not completely unlike Church

share|improve this answer

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.