2015-09-15 59 views
1

我有用於計算在一個遊戲中的得分的數組:附加陣列中的(LUA)

a = {1,7,5,1,2,6,2,3,4,5,5,6,7,7,7} 

的所有數字應被簡單地添加,除了當一個號碼出現幾次,例如7(其中出現4次)它應該被添加爲這樣:

1*7 + 2*7 + 3*7 + 4*7 

所以,一共,陣列 「一」 應該給這個分數:

score = (1*1 + 2*1) + (1*2 + 2*2) + (1*3) + (1*4) + (1*5 + 2*5 + 3*5) + (1*6 + 2*6) + (1*7 + 2*7 + 3*7 + 4*7) 

我不知道從哪裏開始做這件事。這種計算有什麼好方法?

任何幫助表示讚賞。

回答

5

可以在另一個表跟蹤當前乘法器的每個號碼:

function calculateScore(a) 
    local multipliers = {} 
    local score = 0 
    for i,number in ipairs(a) do 
     local multiplier = multipliers[number] or 1 
     multipliers[number] = multiplier + 1 
     score = score + number * multiplier 
    end 
    return score 
end 

local a = {1,7,5,1,2,6,2,3,4,5,5,6,7,7,7} 
local score = calculateScore(a) 
+0

和稍微更緊湊版本:功能FSUM(噸) 局部x = {總和= 0} 爲_, n在ipairs(t)中做 x [n] =(x [n]或0)+ 1 x.sum = x.sum + x [n] * n end return x.sum end – tonypdmtr