Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to get random expressions displaying. For that, I'm starting with addition, multiplication, substraction and division. When trying out this code

 HoldForm[c e d] /. c -> RandomInteger[{1, 15}] /. 
 d -> RandomInteger[{1, 15}] /. 
 e -> RandomChoice[{"-", "+", "/", "*"}]

, I sometimes get indeed expressions as "11 "+" 6" as expected, but I also get

 14 "-"


 "-" 9.

Why is that?

Perhaps anyone has another idea for making randomised arithmetic expressions? Thanks, once again!

share|improve this question
up vote 4 down vote accepted

Try this

HoldForm[op@##] & @@ RandomInteger[{1, 15}, 2] /. 
 op -> RandomChoice[{Plus, Subtract, Times, Divide}]
share|improve this answer
Thank you for your help! One more question: why doesn't this work: HoldForm[Plus @@ ##] &@{a, b} ? Thanks for all information! – Gabriel Sep 9 '13 at 9:27
@Gabriel FullForm of a + b is Plus[a, b], not Plus@@{a, b} – ybeltukov Sep 9 '13 at 12:17

Here is a subtly different form of what ybeltukov proposed:

RandomChoice[{Plus, Subtract, Times, Divide}] /. op_ :>
    HoldForm[op@##] & @@ RandomInteger[{1, 15}, 2]

You'll notice that the rule is used in reverse. I call this the injector pattern. Here is serves an important role of localizing the Symbol op. You could also use HoldPattern[op] -> . . . to do the same.

Here is another option:

Function[op, HoldForm[op@##] & @@ RandomInteger[{1, 15}, 2]] /@ 
  RandomChoice[{Plus, Subtract, Times, Divide}, 10]

enter image description here

share|improve this answer

Your Answer


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.