这回答了用户提出的另一个问题。
SEND + MORE = MONEY,其中每个字符都有一个唯一的数字,并且没有单词以零开头。
select
top 1
S.num as S,
E.num as E,
N.num as N,
D.num as D,
M.num as M,
O.num as O,
R.num as R,
Y.num as Y,
(S.num * 1000 + E.num * 100 + N.num * 10 + D.num) as [SEND],
(M.num * 1000 + O.num * 100 + R.num * 10 + E.num) as MORE,
(S.num * 1000 + E.num * 100 + N.num * 10 + D.num) + (M.num * 1000 + O.num * 100 + R.num * 10 + E.num) as SEND_plus_MORE,
(M.num * 10000 + O.num * 1000 + N.num * 100 + E.num * 10 + Y.num) as [MONEY]
from
Digits as S
join digits as E on E.num <> S.num
join digits as N on N.num <> S.num and N.num <> E.num
join digits as D on D.num <> S.num and D.num <> E.num and D.num <> N.num
join digits as M on M.num <> S.num and M.num <> E.num and M.num <> N.num and M.num <> D.num
join digits as O on O.num <> S.num and O.num <> E.num and O.num <> N.num and O.num <> D.num and O.num <> M.num
join digits as R on R.num <> S.num and R.num <> E.num and R.num <> N.num and R.num <> D.num and R.num <> M.num and R.num <> O.num
join digits as Y on Y.num <> S.num and Y.num <> E.num and Y.num <> N.num and Y.num <> D.num and Y.num <> M.num and Y.num <> O.num and Y.num <> R.num
where
(S.num * 1000 + E.num * 100 + N.num * 10 + D.num)
+ (M.num * 1000 + O.num * 100 + R.num * 10 + E.num)
= (M.num * 10000 + O.num * 1000 + N.num * 100 + E.num * 10 + Y.num)
and S.num <> 0 and M.num <> 0
我在 WHERE 子句中考虑了一些东西来强制执行唯一数字,但我相信这最终会在检查 WHERE 子句之前处理太多的排列。
由于我们只处理最多 10 位数字,我认为最好构建长 ON 子句来代替速度问题。
这是没有疯狂的 ON 子句的 FROM + WHERE 子句。这在我的服务器上运行得慢了很多。
from
Digits as S
cross join digits as E
cross join digits as N
cross join digits as D
cross join digits as M
cross join digits as O
cross join digits as R
cross join digits as Y
where
(S.num * 1000 + E.num * 100 + N.num * 10 + D.num)
+ (M.num * 1000 + O.num * 100 + R.num * 10 + E.num)
= (M.num * 10000 + O.num * 1000 + N.num * 100 + E.num * 10 + Y.num)
and S.num <> 0 and M.num <> 0
and (select max(B.Count) from
(select COUNT(*) as Count from
(select S.num, 's' as letter -- the letters are included to make sure the unions do not merge equivalent rows
UNION select E.num, 'e'
UNION select N.num, 'n'
UNION select D.num, 'd'
UNION select M.num, 'm'
UNION select O.num, 'o'
UNION select R.num, 'r'
UNION select Y.num, 'y') as A
group by A.num
) as B
) = 1