题目: 编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100。
lua实现1:
--这道题其实就是求+、-、“”,三个符号的的组合,若把它们定义成0、1、2,那么就是一个8位3进制数的取值范围。
--用lua的table表示一个8位3进制数,每次循环给加1,若满足结果为100则输出。
local tUnit_3 = {} local digit_max = 8 local parse = {[0] = "+", [1] = "-", [2] = ""} function tUnitAddByDigit(digit)if digit > digit_max then return false end tUnit_3[digit] = tUnit_3[digit] or 0 tUnit_3[digit] = tUnit_3[digit] + 1 if tUnit_3[digit] == 3 then tUnit_3[digit] = 0 return tUnitAddByDigit(digit+1) end --计算结果,若为100则输出 local str = "" for digit = 1, 8 do str = str..digit..parse[tUnit_3[digit] or 0] end str = str .. 9 local fun = loadstring("return "..str) if fun() == 100 then print(str) end return true end
while(true)do if not tUnitAddByDigit(1) then break end end
lua实现2:
local tSort = {} local parse = {[0] = "+", [1] = "-", [2] = ""} function SetSort(index) if index == 9 then local str = "" for digit = 1, 8 do str = str..digit..parse[tSort[digit] or 0] end str = str .. 9 local fun = loadstring("return "..str) if fun() == 100 then print(str) end return end for i = 0, 2 do tSort[index] = i SetSort(index + 1) end end SetSort(1)