aboutsummaryrefslogtreecommitdiff
path: root/challenge-160/deadmarshal/lua/ch-2.lua
blob: 9682d9c6178f87b4c0d20f11ff3701891664e582 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function array_sum(t)
   assert(type(t) == "table", "t must be a table!")
   local sum = 0
   for i=1, #t do sum = sum + t[i] end
   return sum
end

function equilibrium_index(t)
   assert(type(t) == "table", "t must be a table!")
   local left, right, ret = 0, array_sum(t), -1
   for i,j in pairs(t) do
      right = right - j
      if left == right then
	 ret = i
	 break
      end
      left = left + j
   end
   return ret
end

print(equilibrium_index({1,3,5,7,9}))
print(equilibrium_index({1,2,3,4,5}))
print(equilibrium_index({2,4,2}))