How to resolve the algorithm Equilibrium index step by step in the Tcl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Equilibrium index step by step in the Tcl 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 Tcl programming language
Source code in the tcl programming language
proc listEquilibria {list} {
set after 0
foreach item $list {incr after $item}
set result {}
set idx 0
set before 0
foreach item $list {
incr after [expr {-$item}]
if {$after == $before} {
lappend result $idx
}
incr before $item
incr idx
}
return $result
}
set testData {-7 1 5 2 -4 3 0}
puts Equilibria=[join [listEquilibria $testData] ", "]
You may also check:How to resolve the algorithm Prime numbers whose neighboring pairs are tetraprimes step by step in the Raku programming language
You may also check:How to resolve the algorithm Abundant, deficient and perfect number classifications step by step in the Clojure programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bead sort step by step in the zkl programming language
You may also check:How to resolve the algorithm Introspection step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Circles of given radius through two points step by step in the Rust programming language