How to resolve the algorithm Equilibrium index step by step in the Factor programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Equilibrium index step by step in the Factor 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 Factor programming language
Source code in the factor programming language
USE: math.vectors
: accum-left ( seq id quot -- seq ) accumulate nip ; inline
: accum-right ( seq id quot -- seq ) [ <reversed> ] 2dip accum-left <reversed> ; inline
: equilibrium-indices ( seq -- inds )
0 [ + ] [ accum-left ] [ accum-right ] 3bi [ = ] 2map
V{ } swap dup length iota [ [ suffix ] curry [ ] if ] 2each ;
( scratchpad ) { -7 1 5 2 -4 3 0 } equilibrium-indices .
V{ 3 6 }
You may also check:How to resolve the algorithm String append step by step in the Sidef programming language
You may also check:How to resolve the algorithm Deceptive numbers step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Determine if a string is squeezable step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm IBAN step by step in the Nim programming language
You may also check:How to resolve the algorithm Leap year step by step in the sed programming language