How to resolve the algorithm Equilibrium index step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Equilibrium index step by step in the Wren 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 Wren programming language
Source code in the wren programming language
import "./fmt" for Fmt
var equilibrium = Fn.new { |a|
var len = a.count
var equi = []
if (len == 0) return equi // sequence has no indices at all
var rsum = a.reduce { |acc, x| acc + x }
var lsum = 0
for (i in 0...len) {
rsum = rsum - a[i]
if (rsum == lsum) equi.add(i)
lsum = lsum + a[i]
}
return equi
}
var tests = [
[-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
[2, 9, 2],
[1, -1, 1, -1, 1, -1, 1],
[1],
[]
]
System.print("The equilibrium indices for the following sequences are:\n")
for (test in tests) {
Fmt.print("$24n -> $n", test, equilibrium.call(test))
}
You may also check:How to resolve the algorithm Palindrome detection step by step in the Nanoquery programming language
You may also check:How to resolve the algorithm Maze generation step by step in the EDSAC order code programming language
You may also check:How to resolve the algorithm Dining philosophers step by step in the VBA programming language
You may also check:How to resolve the algorithm Averages/Pythagorean means step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Parsing/RPN to infix conversion step by step in the Ruby programming language