How to resolve the algorithm Equilibrium index step by step in the Lua programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Equilibrium index step by step in the Lua programming language
Table of Contents
Problem Statement
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
: 3 is an equilibrium index, because: 6 is also an equilibrium index, because: (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Equilibrium index step by step in the Lua programming language
Source code in the lua programming language
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}))
You may also check:How to resolve the algorithm Loops/For step by step in the MiniScript programming language
You may also check:How to resolve the algorithm Fibonacci word/fractal step by step in the Perl programming language
You may also check:How to resolve the algorithm Rot-13 step by step in the Mirah programming language
You may also check:How to resolve the algorithm Percentage difference between images step by step in the D programming language
You may also check:How to resolve the algorithm Modular arithmetic step by step in the Kotlin programming language