Wolfram 语言

核心语言

测试计算能力

法国电视节目《数字与字母》(Des chiffres et des lettres)和其英语版《倒计时》( Countdown )测试竞争选手的计算能力. 构建该游戏的简单版本,并用全新函数 Groupings 进行解答.

指定可用于执行计算的算数运算.

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

生成一个从给定数字集合中随机选取的 4 个数字的列表.

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

从这些数字和运算中获取的总数也是随机生成的.

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

构建使用每个数字一次的所有可能方法,记住对于某些算数运算需要考虑顺序.

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

利用给定二元运算生成每个排序可能的组合.

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

一些组合由于被 0 除会生成 ComplexInfinity 信息,可以用 Quiet 将其删除.

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

以下为产生要求总数的组合数目.

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

以下为其中可能的组合.

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

有些时候可能不会产生完全相同的总数.

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

但是可以通过使用 Nearest 函数找出最近似的结果.

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

相关范例

de en es fr ja ko pt-br ru