Wolfram Language

Core Language

Test Your Numeracy Skills

The French TV program Des chiffres et des lettres and its English adaptation Countdown test contestants on their numeracy skills. Construct a simple version of this game and solve it with the new function Groupings.

Specify the arithmetic operations that can be used to perform the calculations.

In[1]:=
Click for copyable input
ops = {Plus, Subtract, Times, Divide};

Generate a list of 4 numbers chosen randomly from a given set of numbers.

In[2]:=
Click for copyable input
numbers = RandomChoice[{1, 2, 3, 5, 7, 10}, 4]
Out[2]=

The total to get from these numbers and operations is also generated randomly.

In[3]:=
Click for copyable input
total = RandomInteger[100]
Out[3]=

Construct all possible ways of using each number once, keeping in mind that the order matters for some of the arithmetic operations.

In[4]:=
Click for copyable input
orderings = Flatten[Permutations /@ Subsets[numbers, {4}], 1]
Out[4]=

Generate all possible combinations of each ordering with the given binary operations.

In[5]:=
Click for copyable input
candidates = Groupings[orderings, ops -> 2, HoldForm];

Some candidates produce ComplexInfinity messages due to division by 0, and they can be eliminated by using Quiet.

In[6]:=
Click for copyable input
results = Quiet@ReleaseHold[candidates];

Here are the number of combinations that produce the total requested.

In[7]:=
Click for copyable input
combinations = Thread[Equal[candidates, results]]; Count[Thread[Equal[candidates, results]], _ == total]
Out[7]=

This is one of the possible combinations.

In[8]:=
Click for copyable input
FirstCase[combinations, _ == total]
Out[8]=

It may not be possible to obtain the exact total in some cases.

In[9]:=
Click for copyable input
total2 = 76; Count[combinations, _ == total2]
Out[9]=

But you can look for the best approximations among the results by using the function Nearest.

In[10]:=
Click for copyable input
total2 = 76; Count[combinations, _ == total2]; DeleteCases[results, ComplexInfinity]; DeleteDuplicates@Nearest[%, total2]
Out[10]=

Related Examples

de es fr ja ko pt-br ru zh