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 “-”

or

“-” 9.

Why is that?

Perhaps anyone has another idea for making randomised arithmetic expressions?

Thanks, once again!

=================

=================

2 Answers

2

=================

Try this

HoldForm[op@##] & @@ RandomInteger[{1, 15}, 2] /.

op -> RandomChoice[{Plus, Subtract, Times, Divide}]

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]