aboutsummaryrefslogtreecommitdiff
path: root/challenge-160/deadmarshal/lua/ch-2.lua
diff options
context:
space:
mode:
Diffstat (limited to 'challenge-160/deadmarshal/lua/ch-2.lua')
-rw-r--r--challenge-160/deadmarshal/lua/ch-2.lua24
1 files changed, 24 insertions, 0 deletions
diff --git a/challenge-160/deadmarshal/lua/ch-2.lua b/challenge-160/deadmarshal/lua/ch-2.lua
new file mode 100644
index 0000000000..9682d9c617
--- /dev/null
+++ b/challenge-160/deadmarshal/lua/ch-2.lua
@@ -0,0 +1,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}))