Equilibrium index: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
(Added Lua language for this task)
Line 1,654: Line 1,654:
show equilibrium_index [-7 1 5 2 -4 3 0] ; [4 7]</lang>
show equilibrium_index [-7 1 5 2 -4 3 0] ; [4 7]</lang>


=={{header|Lua}}==
<lang lua>
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({-7, 1, 5, 2, -4, 3, 0}))

</lang>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica indexes are 1-based so the output of this program will be shifted up by one compared to solutions in languages with 0-based arrays.
Mathematica indexes are 1-based so the output of this program will be shifted up by one compared to solutions in languages with 0-based arrays.