1. 程式人生 > >計算一個N個選項中和為X的所有組合數

計算一個N個選項中和為X的所有組合數



下面就是一個最近微信上流傳的一個測試:

假如5塊錢可以買一個女朋友,你會買什麼樣的?下面是每項的價格

有錢-4元, 長得好看-3元, 會做飯-3元, 忠誠-3元, 處女-2元, 溫柔-2元, 活潑可愛-2元, 大長腿-1元, 聰明-1元, 胸大-1元


--計算從1到maxNumber的自然數中取selNum個數的所有組合
function CalcNaturalNumberComb(maxNumber, selNum, tabReturn)
    local tabComb = {}
    comb_natural_number_recursive_func = function(m,k,tab)
        for i=m,k,-1 do
            tabComb[k+1] = i
           
            if k > 1 then
                comb_natural_number_recursive_func(i-1,k-1,tab)
            else
                local tabOut = {}
                local nStart = tonumber(tabComb[1])
                for n=nStart,1,-1 do
                    table.insert(tabOut,tabComb[n+1])
                end
                table.insert(tab,tabOut)
            end
        end
    end

    tabComb = {}
    tabComb[1] = selNum
    comb_natural_number_recursive_func(maxNumber, selNum, tabReturn)
end

TAB_X =
{
    ["有錢"] = 4,
    ["長得好看"] = 3, ["會做飯"] = 3, ["忠誠"] = 3, 
    ["處女"] = 2, ["溫柔"] = 2, ["活潑可愛"] = 2,
    ["大長腿"] = 1, ["聰明"] = 1, ["胸大"] = 1,
}

TAB_NAME = {}
TAB_VAL = {}
for k,v in pairs(TAB_X) do table.insert(TAB_NAME,k) table.insert(TAB_VAL,v) end

local tabCombAll = {}
for i=1,table.count(TAB_X) do
    local tabComb = {}
    CalcNaturalNumberComb(table.count(TAB_X), i, tabComb)
    table.insert(tabCombAll, tabComb)
end

local id = 1
for i=1,#tabCombAll do
    for k=1,#tabCombAll[i] do
        local c = 0
        local s = ""
        for m=1,#tabCombAll[i][k] do
            c = c + TAB_VAL[tabCombAll[i][k][m]]
            s = s .. TAB_NAME[tabCombAll[i][k][m]].."["..TAB_VAL[tabCombAll[i][k][m]].."]"
        end
        if c == 5 then
            print(string.format("%02d.%s", id, s))
            id = id + 1
        end
    end
end