# Wolfram Mathematica

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]:=
`ops = {Plus, Subtract, Times, Divide};`

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

In[2]:=
`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]:=
`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]:=
`orderings = Flatten[Permutations /@ Subsets[numbers, {4}], 1]`
Out[4]=

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

In[5]:=
`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]:=
`results = Quiet@ReleaseHold[candidates];`

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

In[7]:=
```combinations = Thread[Equal[candidates, results]]; Count[Thread[Equal[candidates, results]], _ == total]```
Out[7]=

This is one of the possible combinations.

In[8]:=
`FirstCase[combinations, _ == total]`
Out[8]=

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

In[9]:=
```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]:=
```total2 = 76; Count[combinations, _ == total2]; DeleteCases[results, ComplexInfinity]; DeleteDuplicates@Nearest[%, total2]```
Out[10]=