0

関数を書きたいのですが、やり方がわかりません。

local data ={
[100000000]='string1',
[250000000]='string2',
[500000000]='string3',
}

local calc=780325665

たとえば、calcでデータインデックスのそれぞれを計算したい

result= calc-(500000000+250000000)

結果と data[500000000],data[250000000]= string1 と string2 に報酬を与えるのが好きです

local calc=780325665
for ind,i in pairs(data) do
    repeat
        if calc< 0 then return end
        print(calc,data[ind])
        calc=calc-ind
    until calc < ind
end

それは私が望むようには機能しません、私は私の例のようにしたいです

誰かが私を助けてくれることを願っています。

合計で支払われた公式の金額を計算する関数を作成したいと考えています。これらの番号は私に返されるべきです。例えば。10、25、50、合計 380 あります

so 385 = (7*50) + (3*10) rest 5

local calc=780325665 --only example number
so i have 100000000,250000000,500000000 and total number calc

calc-(500000000+250000000) rest 30325665 because there are no smaller number

短縮できる頻度に応じて、これらの 2 つの数字に報酬を与えます

4

3 に答える 3

0

あなたの質問が正しければ - 次のコードがあなたのために働くはずです -

local data ={
[1]='string1',
[2]='string2',
[10]='string4',
[25]='string3',
}

-- lets get the indices in their increasing order
local indices = {}
for n in pairs(data) do table.insert(indices, n) end
table.sort(indices, function(a, b) return a > b end)

local calc = 97
local result = {}

-- for every index, highest coming first
for _,v in ipairs(indices) do
    -- if calc is bigger than this index
    while calc >= v do
        -- if this index has never been encountered, set it to 1 or add 1 to previous
        result[v] = (result[v] or 0) + 1
        -- reduce calc and check again
        calc = calc - v
    end
end

-- result is your output

これが探していたものでない場合は、質問を編集して詳細を提供してください。おそらく例で。

于 2013-09-10T06:30:29.157 に答える
0

テーブル内のすべての数値を数えて計算しようとしている場合、これが役立つ場合があります。

local count = 0
for k, v in pairs(data) do
     count = count + 1
end

local total = 0
for i = 1, count do
   total = total + data[i]
end

この単純なコードは、テーブル内のすべての数値を数えて計算するのに役立ちます。

于 2013-09-10T09:55:57.690 に答える