Equilibrium index: Difference between revisions

Added Easylang
(Added Easylang)
 
(46 intermediate revisions by 23 users not shown)
Line 35:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">F eqindex(arr)
R (0 .< arr.len).filter(i -> sum(@arr[0.<i]) == sum(@arr[i+1..]))
 
print(eqindex([-7, 1, 5, 2, -4, 3, 0]))</langsyntaxhighlight>
 
{{out}}
Line 44:
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">REPORT equilibrium_index.
 
TYPES: y_i TYPE STANDARD TABLE OF i WITH EMPTY KEY.
Line 57:
LET z = sequences[ i ] IN
NEXT x = COND #( WHEN y = ( total_sum - y - z ) THEN VALUE y_i( BASE x ( i - 1 ) ) ELSE x )
y = y + z ) ).</langsyntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
INT FUNC SumRange(INT ARRAY a INT first,last)
INT sum
INT i
 
sum=0
FOR i=first TO last
DO
sum==+a(i)
OD
RETURN(sum)
 
PROC EquilibriumIndices(INT ARRAY a INT size
INT ARRAY indices INT POINTER indSize)
INT i,left,right
 
indSize^=0
FOR i=0 TO size-1
DO
left=SumRange(a,0,i-1)
right=SumRange(a,i+1,size-1)
IF left=right THEN
indices(indSize^)=i
indSize^==+1
FI
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
INT ARRAY indices(100)
INT indSize
 
EquilibriumIndices(a,size,indices,@indSize)
Print("Array=") PrintArray(a,size)
Print("Equilibrium indices=") PrintArray(indices,indSize)
PutE()
RETURN
 
PROC Main()
INT ARRAY a=[65529 1 5 2 65532 3 0]
INT ARRAY b=[65535 1 65535 1 65535 1 65535]
INT ARRAY c=[1 2 3 4 5 6 7 8 9]
INT ARRAY d=[0]
 
Test(a,7)
Test(b,7)
Test(c,9)
Test(d,1)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Equilibrium_index.png Screenshot from Atari 8-bit computer]
<pre>
Array=[-7 1 5 2 -4 3 0]
Equilibrium indices=[3 6]
 
Array=[-1 1 -1 1 -1 1 -1]
Equilibrium indices=[0 1 2 3 4 5 6]
 
Array=[1 2 3 4 5 6 7 8 9]
Equilibrium indices=[]
 
Array=[0]
Equilibrium indices=[0]
</pre>
 
=={{header|Ada}}==
Line 64 ⟶ 141:
 
equilibrium.ads:
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Vectors;
 
generic
Line 81 ⟶ 158:
function Get_Indices (From : Array_Type) return Index_Vectors.Vector;
 
end Equilibrium;</langsyntaxhighlight>
equilibrium.adb:
<langsyntaxhighlight Adalang="ada">package body Equilibrium is
 
function Get_Indices (From : Array_Type) return Index_Vectors.Vector is
Line 102 ⟶ 179:
end Get_Indices;
 
end Equilibrium;</langsyntaxhighlight>
Test program using two different versions, one with vectors and one with arrays:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Equilibrium;
with Ada.Containers.Vectors;
Line 155 ⟶ 232:
end loop;
Ada.Text_IO.New_Line;
end Main;</langsyntaxhighlight>
{{out}}
(Index_Type is based on 1):
Line 166 ⟶ 243:
{{works with|Ada 2005}}
equilibrium.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Equilibrium is
Line 233 ⟶ 310:
Ada.Text_IO.Put_Line ("X4:" & Seq_Img (X4));
Ada.Text_IO.Put_Line ("Eqs:" & Seq_Img (X4_Result));
end Equilibrium;</langsyntaxhighlight>
{{out}}
<pre>Results:
Line 250 ⟶ 327:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">list
eqindex(list l)
{
Line 274 ⟶ 351:
 
0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 281 ⟶ 358:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">MODE YIELDINT = PROC(INT)VOID;
 
PROC gen equilibrium index = ([]INT arr, YIELDINT yield)VOID:
Line 305 ⟶ 382:
# OD # );
print(new line)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 312 ⟶ 389:
 
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}(ES6 version)
<langsyntaxhighlight lang="applescript">-- equilibriumIndices :: [Int] -> [Int]
on equilibriumIndices(xs)
Line 490 ⟶ 568:
end repeat
return lst
end zip</langsyntaxhighlight>
{{Out}}
<pre>{{3, 6}, {}, {1}, {0, 1, 2, 3, 4, 5, 6}, {0}, {}}</pre>
----
===Straightforward===
<syntaxhighlight lang="applescript">on equilibriumIndices(sequence)
script o
property seq : sequence
property output : {}
end script
set loSum to 0
set hiSum to 0
repeat with value in o's seq
set hiSum to hiSum + value
end repeat
repeat with i from 1 to (count o's seq)
set value to o's seq's item i
set hiSum to hiSum - value
if (hiSum = loSum) then set o's output's end to i
set loSum to loSum + value
end repeat
return o's output
end equilibriumIndices
 
equilibriumIndices({-7, 1, 5, 2, -4, 3, 0})</syntaxhighlight>
 
{{output}}
AppleScript uses 1-based indices.
<syntaxhighlight lang="applescript">{4, 7}</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">eqIndex: function [row][
suml: 0
delayed: 0
sumr: sum row
result: new []
loop.with:'i row 'r [
suml: suml + delayed
sumr: sumr - r
delayed: r
if suml = sumr -> 'result ++ i
]
return result
]
 
data: @[
@[neg 7, 1, 5, 2, neg 4, 3, 0]
@[2 4 6]
@[2 9 2]
@[1 neg 1 1 neg 1 1 neg 1 1]
]
 
loop data 'd ->
print [pad.right join.with:", " to [:string] d 25 "=> equilibrium index:" eqIndex d]</syntaxhighlight>
 
{{out}}
 
<pre>-7, 1, 5, 2, -4, 3, 0 => equilibrium index: [3 6]
2, 4, 6 => equilibrium index: []
2, 9, 2 => equilibrium index: [1]
1, -1, 1, -1, 1, -1, 1 => equilibrium index: [0 1 2 3 4 5 6]</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Equilibrium_index(list, BaseIndex=0){
StringSplit, A, list, `,
Loop % A0 {
Line 508 ⟶ 647:
}
return Res
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">list = -7, 1, 5, 2, -4, 3, 0
MsgBox % Equilibrium_index(list)</langsyntaxhighlight>
{{out}}
<pre>3, 6</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f EQUILIBRIUM_INDEX.AWK
BEGIN {
Line 543 ⟶ 682:
return(str)
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
Line 558 ⟶ 697:
indices: 1 2 3 4 5 6 7
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|Ring}}
<syntaxhighlight lang="vb">arraybase 1
 
dim list = {-7, 1, 5, 2, -4, 3, 0}
print "equilibrium indices are : "; equilibrium(list)
end
 
function equilibrium (l)
r = 0: s = 0
e$ = ""
for n = 1 to l[?]
s += l[n]
next
for i = 1 to l[?]
if r = s - r - l[i] then e$ += string(i-1) + " "
r += l[i]
next
e$ = left(e$, length(e$)-1)
return e$
end function</syntaxhighlight>
{{out}}
<pre>The equilibrium indices are : 3 6</pre>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 601 ⟶ 765:
echo [!equilms!]
goto :EOF
%==/The Function ==%</langsyntaxhighlight>
{{Out}}
<pre>[3 6]
Line 610 ⟶ 774:
=={{header|BBC BASIC}}==
BBC BASIC's '''SUM''' function is useful for this task.
<langsyntaxhighlight lang="bbcbasic"> DIM list(6)
list() = -7, 1, 5, 2, -4, 3, 0
PRINT "Equilibrium indices are " FNequilibrium(list())
Line 622 ⟶ 786:
r += l(i%)
NEXT
= LEFT$(e$)</langsyntaxhighlight>
'''Output:'''
<pre>
Line 629 ⟶ 793:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 672 ⟶ 836:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 705 ⟶ 869:
}
}
}</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">3
6</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <numeric>
Line 750 ⟶ 914:
 
std::for_each(indices.begin(), indices.end(), print<size_t>);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 759 ⟶ 923:
=={{header|Clojure}}==
{{trans|Ocaml}}
<langsyntaxhighlight lang="clojure">(defn equilibrium [lst]
(loop [acc '(), i 0, left 0, right (apply + lst), lst lst]
(if (empty? lst)
Line 766 ⟶ 930:
right (- right x)
acc (if (= left right) (cons i acc) acc)]
(recur acc (inc i) (+ left x) right xs)))))</langsyntaxhighlight>
{{out}}
<pre>
Line 774 ⟶ 938:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun dflt-on-nil (v dflt)
(if v v dflt))
 
Line 788 ⟶ 952:
(if (eql lsum rsum) (push i stack))
(setf lsum (+ lsum (car rest)))
(setf rsum (- rsum (dflt-on-nil (cadr rest) 0)))))</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">(eq-index '(-7 1 5 2 -4 3 0))
(3 6)</langsyntaxhighlight>
 
=={{header|D}}==
===More Functional Style===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.functional;
 
auto equilibrium(Range)(Range r) pure nothrow @safe /*@nogc*/ {
Line 803 ⟶ 967:
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[3, 6]</pre>
Line 810 ⟶ 974:
{{trans|PHP}}
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
size_t[] equilibrium(T)(in T[] items) @safe pure nothrow {
Line 827 ⟶ 991:
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}</langsyntaxhighlight>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Equilibrium_index#Pascal Pascal].
 
=={{header|EasyLang}}==
<syntaxhighlight>
func[] equind a[] .
for v in a[]
sumr += v
.
for i to len a[]
sumr -= a[i]
if suml = sumr
r[] &= i
.
suml += a[i]
.
return r[]
.
print equind [ -7 1 5 2 -4 3 0 ]
</syntaxhighlight>
{{out}}
<pre>
[ 4 7 ]
</pre>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
import system'collections;
Line 862 ⟶ 1,050:
while(en.next())
{
var element := *en.get();
right -= element;
bool found := (left == right);
Line 889 ⟶ 1,077:
}
get Value() = index;
enumerable() => en;
Line 897 ⟶ 1,085:
{
EquilibriumEnumerator.new(new int[]{ -7, 1, 5, 2, -4, 3, 0 })
.forEach:(printingLn)
}</langsyntaxhighlight>
<pre>
3
Line 907 ⟶ 1,095:
{{trans|Ruby}}
computes either side each time.
<langsyntaxhighlight lang="elixir">defmodule Equilibrium do
def index(list) do
last = length(list)
Line 914 ⟶ 1,102:
end)
end
end</langsyntaxhighlight>
 
faster version:
<langsyntaxhighlight lang="elixir">defmodule Equilibrium do
def index(list), do: index(list,0,0,Enum.sum(list),[])
Line 923 ⟶ 1,111:
defp index([h|t],i,left,right,acc) when left==right-h, do: index(t,i+1,left+h,right-h,[i|acc])
defp index([h|t],i,left,right,acc) , do: index(t,i+1,left+h,right-h,acc)
end</langsyntaxhighlight>
 
'''Test:'''
<langsyntaxhighlight lang="elixir">indices = [
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
Line 934 ⟶ 1,122:
Enum.each(indices, fn list ->
IO.puts "#{inspect list} => #{inspect Equilibrium.index(list)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 945 ⟶ 1,133:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM EQUILIBRIUM
 
Line 967 ⟶ 1,155:
PRINT("Equilibrium indices are";RES$)
END PROGRAM
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 974 ⟶ 1,162:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function equilibrium(sequence s)
integer lower_sum, higher_sum
sequence indices
Line 993 ⟶ 1,181:
end function
 
? equilibrium({-7,1,5,2,-4,3,0})</langsyntaxhighlight>
{{out}}
''(Remember that indices are 1-based in Euphoria)''
Line 1,000 ⟶ 1,188:
=={{header|Factor}}==
Executed in the listener. Note that <code>accum-left</code> and <code>accum-right</code> have different outputs than <code>accumulate</code> as they drop the final result.
<langsyntaxhighlight lang="factor">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 ;</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="factor">( scratchpad ) { -7 1 5 2 -4 3 0 } equilibrium-indices .
V{ 3 6 }</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Array indices are 1-based.
<langsyntaxhighlight lang="fortran">program Equilibrium
implicit none
Line 1,031 ⟶ 1,219:
 
end subroutine
end program</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub equilibriumIndices (a() As Integer, b() As Integer)
Line 1,069 ⟶ 1,257:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,079 ⟶ 1,267:
=={{header|Fōrmulæ}}==
 
In [http{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Equilibrium_index this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
[[File:Fōrmulæ - Equilibrium index 01.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
In Fōrmulæ, indices are 1-based so the output of this program will be shifted up by one compared to solutions in languages with 0-based arrays.
 
'''Test cases'''
 
[[File:Fōrmulæ - Equilibrium index 02.png]]
 
[[File:Fōrmulæ - Equilibrium index 03.png]]
 
[[File:Fōrmulæ - Equilibrium index 04.png]]
 
[[File:Fōrmulæ - Equilibrium index 05.png]]
 
[[File:Fōrmulæ - Equilibrium index 06.png]]
 
[[File:Fōrmulæ - Equilibrium index 07.png]]
 
[[File:Fōrmulæ - Equilibrium index 08.png]]
 
[[File:Fōrmulæ - Equilibrium index 09.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,121 ⟶ 1,329:
}
return
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,129 ⟶ 1,337:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Random (randomRIO)
import Data.List (elemIndicesfindIndices, takeWhile)
import Control.Monad (replicateM)
import Control.Arrow ((&&&))
 
equilibr xs =
findIndices (\(a, b) -> sum a == sum b) . takeWhile (not . null . snd) $
elemIndices True .
map (\(a, b) -> sum a == sum b) . takeWhile (not . null . snd) $
flip ((&&&) <$> take <*> (drop . pred)) xs <$> [1 ..]
 
langeSliert = replicateM 2000 (randomRIO (-15, 15) :: IO Int) >>= print . equilibr</langsyntaxhighlight>
Small example
<langsyntaxhighlight lang="haskell">*Main> equilibr [-7, 1, 5, 2, -4, 3, 0]
[3,6]</langsyntaxhighlight>
Long random list in langeSliert (several tries for this one)
<langsyntaxhighlight lang="haskell">*Main> langeSliert
[231,245,259,265,382,1480,1611,1612]</langsyntaxhighlight>
 
 
Or, using default Prelude functions:
 
<langsyntaxhighlight lang="haskell">equilibriumIndices :: [Int] -> [Int]
equilibriumIndices xs =
zip3
let matchIndex (x, y, i) a
(scanl1 (+) xs) -- |Sums xfrom ==the y = (i : a)left
(scanr1 (+) xs) -- |Sums otherwisefrom =the aright
[0 ..] -- Indices
in foldr
>>= (\(x, y, i) -> [i | x == y])
matchIndex
[]
(zip3
(scanl1 (+) xs) -- Sums from the left
(scanr1 (+) xs) -- Sums from the right
[0 ..] -- Indices
)
 
--------------------------- TEST--- -------------------------
main :: IO ()
main =
mapM_
print
$ equilibriumIndices
(equilibriumIndices <$>
<$> [ [-7, 1, 5, 2, -4, 3, 0],
, [2, 4, 6],
, [2, 9, 2],
, [1, -1, 1, -1, 1, -1, 1],
, [1],
, []
])</langsyntaxhighlight>
{{Out}}
<pre>[3,6]
Line 1,186 ⟶ 1,387:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
L := if *arglist > 0 then arglist else [-7, 1, 5, 2, -4, 3, 0] # command line args or default
every writes( "equilibrium indicies of [ " | (!L ||" ") | "] = " | (eqindex(L)||" ") | "\n" )
Line 1,201 ⟶ 1,402:
l +:= L[i] # sum of left side
}
end</langsyntaxhighlight>
{{out}}
<pre>equilibrium indicies of [ -7 1 5 2 -4 3 0 ] = 4 7</pre>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">equilidx=: +/\ I.@:= +/\.</langsyntaxhighlight>
{{out|Example use}}
<langsyntaxhighlight lang="j"> equilidx _7 1 5 2 _4 3 0
3 6</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">
public class Equlibrium {
public static void main(String[] args) {
Line 1,237 ⟶ 1,438:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,247 ⟶ 1,448:
 
===ES5===
<langsyntaxhighlight lang="javascript">function equilibrium(a) {
var N = a.length, i, l = [], r = [], e = []
for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i<N; i++)
Line 1,265 ⟶ 1,466:
].forEach(function(x) {
console.log(equilibrium(x))
});</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[[3,6],[],[1],[0,1,2,3,4,5,6],[0],[]]</langsyntaxhighlight>
 
===ES6 Procedural===
Two pass O(n), returning only the first equilibrium index.
<langsyntaxhighlight JavaScriptlang="javascript">function equilibrium(arr) {
let sum = arr.reduce((a, b) => a + b);
let leftSum = 0;
Line 1,287 ⟶ 1,488:
return -1;
}
</syntaxhighlight>
</lang>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">3, -1, 1, 0, 0</langsyntaxhighlight>
 
===ES6 Functional===
 
A composition of pure generic functions, returning '''all''' equilibrium indices.
 
<langsyntaxhighlight lang="javascript">(() => {
'"use strict'";
 
// ------------- ALL EQUILIBRIUM INDICES -------------
 
// equilibriumIndices :: [Int] -> [Int]
const equilibriumIndices = xs =>
zip(scanl1(add)(xs))(
scanl1(add)(xs)
)(
scanr1(add)(xs)
).reduceRight((a, xy, i) =>
xy[0] === xy[1] ? .reduceRight(
(a, xy, i) => xy[0] === xy[1] ? (
[i, ...a]
) : a, []);
);
 
 
// ------------------------TEST------------------------
// ---------------------- TEST -----------------------
const main = () => {
const main = () => [
console.log(JSON.stringify([
[-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
Line 1,316 ⟶ 1,523:
[1],
[]
].map(equilibriumIndices)));compose(
JSON.stringify,
// -> [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []]
equilibriumIndices
};
))
 
.join("\n");
// -> [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []]
 
// -----------------GENERIC FUNCTIONS------------------
 
// ---------------- GENERIC FUNCTIONS ----------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
 
// add (+) :: Num a => a -> a -> a
Line 1,336 ⟶ 1,537:
// Curried addition.
b => a + b;
 
 
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
 
 
// scanl :: (b -> a -> b) -> b -> [a] -> [b]
const scanl = f => startValue => xs =>
// scanlThe isseries likeof foldlinterim orvalues reduce, butarising
// returnsfrom a successioncatamorphism. ofParallel intermediateto foldl.
// valuesxs.reduce((a, buildingx) from=> the left.{
v => xs => xs.reduce((a, x) => {
const v = f(a[0])(x);
return Tuple(v)(a[1].concat(v));
}, Tuple(v)([v]))[1];
 
// scanr :: (b -> a -> b) ->return b ->[v, a[a1] -> [b.concat(v)];
}, [startValue, [startValue]])[1];
const scanr = f =>
 
// scanr is like foldr or reduceRight, but
// returns a succession of intermediate
// values, building from the right.
v => xs => xs.reduceRight((a, x) => {
const v = f(x)(a[0]);
return Tuple(v)([v].concat(a[1]));
}, Tuple(v)([v]))[1];
 
// scanl1 :: (a -> a -> a) -> [a] -> [a]
const scanl1 = f =>
// scanl1 is a variant of scanl that has no
// seed-starting value argument, and assumes that.
// xs is not empty.
xs => xs.length > 0 ? (
scanl(f)(
Line 1,367 ⟶ 1,569:
)(xs.slice(1))
) : [];
 
 
// scanr :: (a -> b -> b) -> b -> [a] -> [b]
const scanr = f =>
startValue => xs => xs.reduceRight(
(a, x) => {
const v = f(x)(a[0]);
 
return [v, [v].concat(a[1])];
}, [startValue, [startValue]]
)[1];
 
 
// scanr1 :: (a -> a -> a) -> [a] -> [a]
Line 1,378 ⟶ 1,592:
)(xs.slice(0, -1))
) : [];
 
 
// zip :: [a] -> [b] -> [(a, b)]
const zip = xs =>
// The paired members of xs and ys, up to
// the length of the shorter of the two lists.
ys => Array.from({
length: Math.min(xs.length, ys.length)
}, (_, i) => Tuple([xs[i])(, ys[i])]);
 
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[[3,6],[],[1],[0,1,2,3,4,5,6],[0],[]]</pre>
[]
[1]
[0,1,2,3,4,5,6]
[0]
[]</pre>
 
=={{header|jq}}==
{{works with | jq}}
The following implementation will work with jq 1.4 but for input
''Also works with gojq, the Go implementation of jq, and jaq''
arrays larger than 1e4 in length, a version of jq with tail-call
optimization (TCO) should probably be used.
 
`equilibrium_indices` is defined as a 0-arity filter that emits answers as a stream, as is idiomatic in jq.
Since the task description indicates that the array might be very long:
* the implementation uses a 0-arity inner function to do the heavy lifting;
* the algorithm walks along the array so as to minimize both memory requirements and the number of arithmetic operations;
* the answers are emitted as a stream.
 
<syntaxhighlight lang="jq"># The index origin is 0 in jq.
The top-level function is defined as a 0-arity filter that emits answers as a stream, as is idiomatic in jq.
<lang jq># The index origin is 0 in jq.
def equilibrium_indices:
. as $in
def indices(a; mx):
| add as $add
def report: # [i, headsum, tailsum]
| foreach .[range(0];length) as $i (
|[0, if0, $iadd]; == mx# then empty #[before, allpivot, doneafter]
$in[$i] as else$x | [.[0]+.[1], as$x, .[2] - $hx];
if .[0] |== (.[2] -then a[$i]) aselse $tempty end) ;
</syntaxhighlight>
| (if $h == $t then $i else empty end),
( [ $i + 1, $h + a[$i], $t ] | report )
end;
[0, 0, (a|add)] | report;
. as $in | indices($in; $in|length);</lang>
'''Example 1:'''
<langsyntaxhighlight lang="jq">[-7, 1, 5, 2, -4, 3, 0] | equilibrium_indices</langsyntaxhighlight>
{{out}}
$ jq -M -n -f equilibrium_indices.jq
Line 1,422 ⟶ 1,636:
6
'''Example 2:'''
<langsyntaxhighlight lang="jq">def count(g): reduce g as $i (0; .+1);
 
# Create an array of length n with "init" elements:
def array(n;init): reduce range(0;n) as $i ([]; . + [0]);
 
count( array(1e410000;0) | equilibrium_indices )</langsyntaxhighlight>
{{out}}
$ jq -M -n -f equilibrium_indices.jq
Line 1,435 ⟶ 1,649:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function equindex2pass(data::Array)
rst = Vector{Int}(0)
suml, sumr, ddelayed = 0, sum(data), 0
Line 1,451 ⟶ 1,665:
@show equindex2pass([1, -1, 1, -1, 1, -1, 1])
@show equindex2pass([1, 2, 2, 1])
@show equindex2pass([-7, 1, 5, 2, -4, 3, 0])</langsyntaxhighlight>
 
{{out}}
Line 1,459 ⟶ 1,673:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> f:{&{(+/y# x)=+/(y+1)_x}[x]'!#x}
f -7 1 5 2 -4 3 0
Line 1,471 ⟶ 1,685:
f 1 -1 1 -1 1 -1 1
0 1 2 3 4 5 6</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
fun equilibriumIndices(a: IntArray): MutableList<Int> {
Line 1,498 ⟶ 1,712:
else -> println("The equilibrium indices are : ${ei.joinToString(", ")}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,506 ⟶ 1,720:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
a(0)=-7
a(1)=1
Line 1,533 ⟶ 1,747:
if len(EQindex$)>0 then EQindex$=mid$(EQindex$, 1, len(EQindex$)-2) 'remove last ", "
end function
</syntaxhighlight>
</lang>
{{out}}
<pre>EQ Indices are 3, 6 </pre>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to equilibrium.iter :i :before :after :tail :ret
if equal? :before :after [make "ret lput :i :ret]
if empty? butfirst :tail [output :ret]
Line 1,547 ⟶ 1,761:
end
 
show equilibrium_index [-7 1 5 2 -4 3 0] ; [4 7]</langsyntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
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}))
 
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica indexes are 1-based so the output of this program will be shifted up by one compared to solutions in languages with 0-based arrays.
<langsyntaxhighlight Mathematicalang="mathematica">equilibriumIndex[data_]:=Reap[
Do[If[Total[data[[;; n - 1]]] == Total[data[[n + 1 ;;]]],Sow[n]],
{n, Length[data]}]][[2, 1]]</langsyntaxhighlight>
{{out|Usage}}
<pre>equilibriumIndex[{-7 , 1, 5 , 2, -4 , 3, 0}]
Line 1,560 ⟶ 1,800:
=={{header|MATLAB}}==
MATLAB arrays are 1-based so the output of this program will be shifted up by one compared to solutions in languages with 0-based arrays.
<langsyntaxhighlight MATLABlang="matlab">function indicies = equilibriumIndex(list)
 
indicies = [];
Line 1,570 ⟶ 1,810:
end
 
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> equilibriumIndex([-7 1 5 2 -4 3 0])
 
ans =
 
4 7</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,617 ⟶ 1,857:
return
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,629 ⟶ 1,869:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import math, sequtils, strutils
 
iterator eqindex(data: openArray[int]): int =
var suml, ddelayed = 0
var sumr = sum(data)
Line 1,640 ⟶ 1,880:
if suml == sumr:
yield i
 
const d = @[@[-7, 1, 5, 2, -4, 3, 0],
@[2, 4, 6],
@[2, 9, 2],
@[1, -1, 1, -1, 1, -1, 1]]
 
for data in d:
echo "d = [", data.join(", "), ']'
echo "eqIndex(d) -> [", toSeq(eqindex(data)).join(", "), ']'</langsyntaxhighlight>
 
{{out}}
<pre>d = [-7, 1, 5, 2, -4, 3, 0]
eqIndex(d) -> [3, 6]
d = [2, 4, 6]
eqIndex(d) -> []
d = [2, 9, 2]
eqIndex(d) -> [1]
d = [1, -1, 1, -1, 1, -1, 1]
eqIndex(d) -> [0, 1, 2, 3, 4, 5, 6]</pre>
 
=={{header|Objeck}}==
{{Trans|Java}}
<langsyntaxhighlight lang="objeck">class Rosetta {
function : Main(args : String[]) ~ Nil {
sequence := [-7, 1, 5, 2, -4, 3, 0];
Line 1,675 ⟶ 1,925:
};
}
}</langsyntaxhighlight>
 
Output:
Line 1,684 ⟶ 1,934:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let lst = [ -7; 1; 5; 2; -4; 3; 0 ]
let sum = List.fold_left ( + ) 0 lst
 
Line 1,698 ⟶ 1,948:
print_string "Results:";
List.iter (Printf.printf " %d") res;
print_newline ()</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,704 ⟶ 1,954:
Oforth collections are 1-based
 
<langsyntaxhighlight Oforthlang="oforth">: equilibrium(l)
| ls rs i e |
0 ->ls
Line 1,712 ⟶ 1,962:
rs e - dup ->rs ls == ifTrue: [ i over add ]
ls e + ->ls
] ;</langsyntaxhighlight>
 
{{out}}
Line 1,722 ⟶ 1,972:
=={{header|PARI/GP}}==
This uses 1-based vectors instead of 0-based arrays; subtract 1 from each index if you prefer the other style.
<langsyntaxhighlight lang="parigp">equilib(v)={
my(a=sum(i=2,#v,v[i]),b=0,u=[]);
for(i=1,#v-1,
Line 1,730 ⟶ 1,980:
);
if(b,u,concat(u,#v))
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program EquilibriumIndexDemo(output);
 
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
 
function ArraySum(list: array of integer; first, last: integer): integer;
Line 1,739 ⟶ 1,991:
i: integer;
begin
ArraySumResult := 0;
for i := first to last do // not taken if first > last
ArraySumResult := ArraySumResult + list[i];
end;
 
Line 1,766 ⟶ 2,018:
EquilibriumIndex(numbers, low(numbers));
writeln;
end.</langsyntaxhighlight>
{{out}}
<pre>:> ./EquilibriumIndex
Line 1,775 ⟶ 2,027:
slightly modified.Calculating the sum only once.Using a zero-based array type.Data type could be any type of signed integer or float.
But beware, that during building the sum, the limits of the data type mustn't be violated.
<langsyntaxhighlight lang="pascal">Program EquilibriumIndexDemo(output);
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
type
Line 1,860 ⟶ 2,112:
numbers[i]:= 0;
TestRun(numbers);
end.</langsyntaxhighlight>{{out}}<pre>List of numbers: -7 1 5 2 -4 3 0
Equilibirum indices: 3 6
 
Line 1,868 ⟶ 2,120:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">sub eq_index {
my ( $i, $sum, %sums ) = ( 0, 0 );
 
Line 1,882 ⟶ 2,134:
print eq_index qw( 2 4 6 ); # (no eq point)
print eq_index qw( 2 9 2 ); # 1
print eq_index qw( 1 -1 1 -1 1 -1 1 ); # 0 1 2 3 4 5 6</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function equilibrium(sequence s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
atom lower_sum = 0
<span style="color: #008080;">function</span> <span style="color: #000000;">equilibrium</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
atom higher_sum = sum(s)
<span style="color: #004080;">atom</span> <span style="color: #000000;">lower_sum</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
sequence res = {}
<span style="color: #000000;">higher_sum</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
for i=1 to length(s) do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
higher_sum -= s[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if lower_sum=higher_sum then
<span style="color: #000000;">higher_sum</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
res &= i
<span style="color: #008080;">if</span> <span style="color: #000000;">lower_sum</span><span style="color: #0000FF;">=</span><span style="color: #000000;">higher_sum</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span>
lower_sum += s[i]
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #000000;">lower_sum</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
? equilibrium({-7,1,5,2,-4,3,0})</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">equilibrium</span><span style="color: #0000FF;">({-</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
(Remember that indices are 1-based in Phix)
Line 1,907 ⟶ 2,162:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$arr = array(-7, 1, 5, 2, -4, 3, 0);
 
Line 1,924 ⟶ 2,179:
echo "# results:\n";
foreach (getEquilibriums($arr) as $r) echo "$r, ";
?></langsyntaxhighlight>
{{out}}
<pre>
Line 1,930 ⟶ 2,185:
3, 6,
</pre>
 
=={{header|Picat}}==
Note: Picat is 1-based.
 
===Prolog-style===
{{trans|Prolog}}
<syntaxhighlight lang="picat">equilibrium_index1(A, Ix) =>
append(Front, [_|Back], A),
sum(Front) = sum(Back),
Ix = length(Front)+1. % give 1 based index</syntaxhighlight>
 
===Loop approach===
{{trans|Java}}
<syntaxhighlight lang="picat">equilibrium_index2(A, Ix) =>
Len = A.length,
Ix1 = [],
TotalSum = sum(A),
RunningSum = 0,
foreach(I in 1..Len)
AI = A[I],
if TotalSum - RunningSum - AI == RunningSum then
Ix1 := Ix1 ++ [I]
end,
RunningSum := RunningSum + AI
end,
Ix = Ix1.</syntaxhighlight>
 
Test the approaches.
<syntaxhighlight lang="picat">go =>
As = [
[-7, 1, 5, 2, -4, 3, 0], % 4 7
[ 2, 4, 6], % (no equilibrium point)
[ 0, 2, 4, 0, 6, 0], % 4
[ 2, 9, 2], % 2
[ 1, -1, 1, -1, 1, -1, 1] % 1 2 3 4 5 6 7
],
foreach(A in As)
println(a=A),
All1 = findall(Ix1, equilibrium_index1(A,Ix1)),
println(all1=All1),
 
equilibrium_index2(A,All2),
println(all2=All2),
nl
end,
 
% A larger random instance
print("A larger random instance:"),
_ = random2(),
N = 5001,
Random = [random(-10,10) : _ in 1..N],
% println(Random),
 
time(R1 = findall(IxR1, equilibrium_index1(Random,IxR1))),
println(r1=R1),
 
time(equilibrium_index2(Random,R2)),
println(r2=R2),
 
nl.</syntaxhighlight>
 
{{out}}
<pre>a = [-7,1,5,2,-4,3,0]
all1 = [4,7]
all2 = [4,7]
 
a = [2,4,6]
all1 = []
all2 = []
 
a = [0,2,4,0,6,0]
all1 = [4]
all2 = [4]
 
a = [2,9,2]
all1 = [2]
all2 = [2]
 
a = [1,-1,1,-1,1,-1,1]
all1 = [1,2,3,4,5,6,7]
all2 = [1,2,3,4,5,6,7]
 
A larger random instance:
 
CPU time 0.113 seconds.
 
r1 = [115,372,4082,4254,4258,4261]
 
CPU time 0.019 seconds.
 
r2 = [115,372,4082,4254,4258,4261]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de equilibria (Lst)
(make
(let Sum 0
(for ((I . L) Lst L (cdr L))
(and (= Sum (sum prog (cdr L))) (link I))
(inc 'Sum (car L)) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (equilibria (-7 1 5 2 -4 3 0))
Line 1,948 ⟶ 2,294:
{{works with|PowerShell|2}}
In real life in PowerShell, one would likely leverage pipelines, ForEach-Object, Where-Object, and Measure-Object for tasks such as this. Normally in PowerShell, speed is an important, but not primary consideration, and the advantages of pipelines tend to outweigh the overhead incurred. However, for this particular task, keeping in mind that “the sequence may be very long,” this code was optimized primarly for speed.
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-EquilibriumIndex ( $Sequence )
{
Line 1,971 ⟶ 2,317:
return $EqulibriumIndex
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-EquilibriumIndex -7, 1, 5, 2, -4, 3, 0
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,983 ⟶ 2,329:
=={{header|Prolog}}==
 
<langsyntaxhighlight lang="prolog">equilibrium_index(List, Index) :-
append(Front, [_|Back], List),
sumlist(Front, Sum),
sumlist(Back, Sum),
length(Front, Len),
Index is Len.</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="prolog">?- equilibrium_index([-7, 1, 5, 2, -4, 3, 0], Index).
Index = 3 ;
Index = 6 ;
false.</langsyntaxhighlight>
 
=={{header|PureBasic}}==
{{trans|Java}}
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define i, c=CountProgramParameters()-1
For i=0 To c
Line 2,012 ⟶ 2,358:
If LSum=RSum: PrintN(Str(i)): EndIf
Next i
EndIf</langsyntaxhighlight>
{{out}}
<pre>> Equilibrium.exe -7 1 5 2 -4 3 0
Line 2,021 ⟶ 2,367:
===Two Pass===
Uses an initial summation of the whole list then visits each item of the list adding it to the left-hand sum (after a delay); and subtracting the item from the right-hand sum. I think it should be quicker than algorithms that scan the list creating left and right sums for each index as it does ~2N add/subtractions rather than n*n.
<langsyntaxhighlight lang="python">def eqindex2Pass(data):
"Two pass"
suml, sumr, ddelayed = 0, sum(data), 0
Line 2,029 ⟶ 2,375:
ddelayed = d
if suml == sumr:
yield i</langsyntaxhighlight>
===Multi Pass===
This is the version that does more summations, but may be faster for some sizes of input as the sum function is implemented in C internally:
<langsyntaxhighlight lang="python">def eqindexMultiPass(data):
"Multi pass"
for i in range(len(data)):
suml, sumr = sum(data[:i]), sum(data[i+1:])
if suml == sumr:
yield i</langsyntaxhighlight>
Shorter alternative:
<langsyntaxhighlight lang="python">def eqindexMultiPass(s):
return [i for i in xrange(len(s)) if sum(s[:i]) == sum(s[i+1:])]
 
print eqindexMultiPass([-7, 1, 5, 2, -4, 3, 0])</langsyntaxhighlight>
===One Pass===
This routine would need careful evaluation against the two-pass solution above as, although it only runs through the data once, it may create a dict that is as long as the input data in its worst case of an input of say a simple 1, 2, 3, ... counting sequence.
<langsyntaxhighlight lang="python">from collections import defaultdict
 
def eqindex1Pass(data):
Line 2,053 ⟶ 2,399:
l += c
h[l * 2 - c].append(i)
return h[l]</langsyntaxhighlight>
===Tests===
<langsyntaxhighlight lang="python">f = (eqindex2Pass, eqindexMultiPass, eqindex1Pass)
d = ([-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
Line 2,064 ⟶ 2,410:
print("d = %r" % data)
for func in f:
print(" %16s(d) -> %r" % (func.__name__, list(func(data))))</langsyntaxhighlight>
{{out|Sample output}}
<pre>d = [-7, 1, 5, 2, -4, 3, 0]
Line 2,088 ⟶ 2,434:
 
The ''right'' scan can be derived from the left as a map or equivalent list comprehension:
<langsyntaxhighlight lang="python">"""Equilibrium index"""
 
from itertools import (accumulate)
Line 2,096 ⟶ 2,442:
def equilibriumIndices(xs):
'''List indices at which the sum of values to the left
equals the sum of values to the right.'''
'''
def go(xs):
'''Left scan from accumulate, right scan derived from left'''
right scan derived from left
'''
ls = list(accumulate(xs))
n = ls[-1]
return [i for (i, (x, y)) in enumerate(zip(
lsi for (i, (x, y)) in enumerate(zip(
[n] + [n - x for x in ls[0:-1]],
)) if [n] + [n - x for x ==in yls[0:-1]]
)) if x == y
]
return go(xs) if xs else []
 
 
# TEST ------------------------- TEST -------------------------
# main :: IO ()
def main():
Line 2,126 ⟶ 2,477:
 
 
# GENERIC ------------------------- GENERIC ------------------------
 
 
# tabulated :: String -> (a -> b) -> [a] -> String
def tabulated(s):
'''heading -> function -> input List -> tabulated output string'''
-> tabulated output string
def go(f, xs):
'''
def go(f):
def width(x):
return len(str(x))
wdef = width(maxcols(xs, key=width)):
return s + '\n' +w '\n'.join= width([max(xs, key=width))
str(x).rjust(w,return ' ')s + ' -> \n' + str'\n'.join(f(x)) for x in xs[
str(x).rjust(w, ' ') + ' -> ' + str(f(x))
])
return lambda f: lambda xs: go(f, for x in xs)
])
return cols
return go
 
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Equilibrium indices:
Line 2,153 ⟶ 2,508:
[1] -> [0]
[] -> []</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ dip [ [] [] 0 ]
witheach
[ + dup dip join ]
over [] swap
witheach
[ dip over - join ]
join
-1 split drop
witheach
[ over i^ peek = if
[ dip [ i^ join ] ] ]
drop ] is equilibria ( [ --> [ )
 
' [ -7 1 5 2 -4 3 0 ] equilibria echo</syntaxhighlight>
 
{{out}}
 
<pre>[ 3 6 ]</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (subsums xs)
Line 2,171 ⟶ 2,547:
 
(equivilibrium '(-7 1 5 2 -4 3 0))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="racket">
'(3 6)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub equilibrium_index(@list) {
my ($left,$right) = 0, [+] @list;
 
Line 2,190 ⟶ 2,566:
 
my @list = -7, 1, 5, 2, -4, 3, 0;
.say for equilibrium_index(@list).grep(/\d/);</langsyntaxhighlight>
And here's an FP solution that manages to remain O(n):
<syntaxhighlight lang="raku" perl6line>sub equilibrium_index(@list) {
my @a = [\+] @list;
my @b = reverse [\+] reverse @list;
^@list Zxx (@a »==« @b);
}</langsyntaxhighlight>
The <tt>[\+]</tt> is a reduction that returns a list of partial results. The <tt>»==«</tt> is a vectorized equality comparison; it returns a vector of true and false. The <tt>Zxx</tt> is a zip with the list replication operator, so we return only the elements of the left list where the right list is true (which is taken to mean 1 here). And the <tt>^@list</tt> is just shorthand for <tt>0 ..^ @list</tt>. We could just as easily have used <tt>@list.keys</tt> there.
=== Single-pass solution ===
Line 2,209 ⟶ 2,585:
Therefore (by substituting L for R), L + C + L == S at all equilibrium points.<br>
Restated, 2L + C == S.
<syntaxhighlight lang="raku" perl6line># Original example, with expanded calculations:
0 1 2 3 4 5 6 # Index
-7 1 5 2 -4 3 0 # C (Value at index)
0 -7 -6 -1 1 -3 0 # L (Sum of left)
-7 -13 -7 0 -2 -3 0 # 2L+C</langsyntaxhighlight>
If we build a hash as we walk the list, with 2L+C as hash keys, and arrays of C-indexes as hash values, we get:
<syntaxhighlight lang="raku" perl6line>{
-7 => [ 0, 2 ],
-13 => [ 1 ],
Line 2,221 ⟶ 2,597:
-2 => [ 4 ],
-3 => [ 5 ],
}</langsyntaxhighlight>
After we have finished walking the list, we will have the sum (S), which we look up in the hash. Here S=0, so the equilibrium points are 3 and 6.
 
Note: In the code below, it is more convenient to calculate 2L+C *after* L has already been incremented by C; the calculation is simply 2L-C, because each L has an extra C in it. 2(L-C)+C == 2L-C.
<syntaxhighlight lang="raku" perl6line>sub eq_index ( *@list ) {
my $sum = 0;
 
Line 2,239 ⟶ 2,615:
say eq_index < 2 4 6 >; # (no eq point)
say eq_index < 2 9 2 >; # 1
say eq_index < 1 -1 1 -1 1 -1 1 >; # 0 1 2 3 4 5 6</langsyntaxhighlight>
The <tt>.classify</tt> method creates a hash, with its code block's return value as key. Each hash value is an Array of all the inputs that returned that key.
 
We could have used <tt>.pairs</tt> instead of <tt>.keys</tt> to save the cost of <tt>@list</tt> lookups, but that would change each <tt>%h</tt> value to an Array of Pairs, which would complicate the return line.
=={{header|Red}}==
<langsyntaxhighlight Rebollang="rebol">Red []
eqindex: func [a [block!]] [
collect [
Line 2,252 ⟶ 2,628:
prin "(1 based) equ indices are: "
probe eqindex [-7 1 5 2 -4 3 0]
</syntaxhighlight>
</lang>
{{out}}
<pre>(1 based) equ indices are: [4 7]</pre>
 
=={{header|ReScript}}==
<syntaxhighlight lang="rescript">let arr = [-7, 1, 5, 2, -4, 3, 0]
let sum = Js.Array2.reduce(arr, \"+", 0)
let len = Js.Array.length(arr)
 
let rec aux = (acc, i, left, right) => {
if (i >= len) { acc } else {
let x = arr[i]
let right = right - x
if (left == right) {
let _ = Js.Array2.push(acc, i)
}
aux(acc, i+1, (left + x), right)
}
}
let res = aux([], 0, 0, sum)
Js.log("Results:")
Js.Array2.forEach(res, Js.log)</syntaxhighlight>
 
=={{header|REXX}}==
===version 1===
This REXX version utilizes a &nbsp; ''zero-based'' &nbsp; stemmed array to mimic the illustrative example in this Rosetta Code task's
<br>prologue, &nbsp; which uses a &nbsp; ''zero-based'' &nbsp; index.
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the equilibrium index for a numeric array (list).*/
parse arg x /*obtain the optional arguments from CL*/
if x='' then x= copies(" 7 -7", 50) 7 /*Not specified? Then use the default.*/
say ' array list: ' space(x) /*echo the array list to the terminal. */
#= words(x) /*the number of elements in the X list.*/
do j=0 for #; @.j= word(x, j+1) /*zero─start is for zero─based array. */
end /*j*/ /* [↑] assign @.0 @.1 @.3 ··· */
say /* ··· and also display a blank line. */
answer= equilibriumIDX(); w= words(answer) /*calculate the equilibrium index. */
say 'equilibrium' word("(none) index: indices:", 1 + (w>0) + (w>1)) answer
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
equilibriumIDX: $=; do i=0 for #; sum= 0
do k=0 for #; sum= sum + @.k * sign(k-i); end /*k*/
if sum==0 then $= $ i
end /*i*/ /* [↑] Zero? Found an equilibrium index*/
return $ /*return equilibrium list (may be null)*/</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> -7 &nbsp; 1 &nbsp; 5 &nbsp; 2 &nbsp; -4 &nbsp; 3 &nbsp; 0 </tt>}}
<pre>
array list: -7 1 5 2 -4 3 0
Line 2,282 ⟶ 2,678:
equilibrium indices: 3 6
</pre>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 2 &nbsp; 9 &nbsp; 2 </tt>}}
<pre>
array list: 2 9 2
Line 2,288 ⟶ 2,684:
equilibrium index: 1
</pre>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 5 &nbsp; 4 &nbsp; 4 &nbsp; 5 </tt>}}
<pre>
array list: 5 4 4 5
Line 2,294 ⟶ 2,690:
equilibrium (none)
</pre>
'''{{out|output''' |text=&nbsp; when using the default input:}}
<pre>
array list: 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7 -7 7
Line 2,302 ⟶ 2,698:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 30.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 2,334 ⟶ 2,730:
eil=eil im1
End
Return eil</langsyntaxhighlight>
'''output'''
<pre> array list: -7 1 5 2 -4 3 0
Line 2,350 ⟶ 2,746:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
list = [-7, 1, 5, 2, -4, 3, 0]
see "equilibrium indices are : " + equilibrium(list) + nl
Line 2,365 ⟶ 2,761:
e = left(e,len(e)-1)
return e
</syntaxhighlight>
</lang>
Output:
<pre>
equilibrium indices are : 3,6
</pre>
 
=={{header|RPL}}==
{| class="wikitable"
! RPL code
! Comment
|-
|
0 SWAP + → seq
≪ { } 0 seq ∑LIST
2 seq SIZE '''FOR''' j
seq j GET - SWAP seq j 1 - GET + SWAP
'''IF''' DUP2 == '''THEN''' ROT j 2 - + ROT ROT '''END'''
'''NEXT''' DROP2
≫ ≫ ‘'''EQIDX'''’ STO
|
'''EQIDX''' ''( { A0..An } -- { equilibrium index } ) ''
add zero at list head to avoid GET error at first loop
left = 0 ; right = A0+A1+...An
loop from j=2 to length(seq) e.g. A0 to An
right -= seq[j] ; left += A[j-1]
if left = right then append j-2 to index list
drop left and right
return list
|}
{ -7 1 5 2 -4 3 0 } EQIDX
{{out}}
<pre>
1: { 3 6 }
</pre>
 
=={{header|Ruby}}==
 
{{works with|Ruby|1.8.7}}
;Functional Style
<langsyntaxhighlight lang="ruby">def eq_indices(list)
list.each_index.select do |i|
list[0...i].inject(0, :+)sum == list[i+1..-1].inject(0, :+)sum
end
end</langsyntaxhighlight>
;Tail Recursion
* This one would be good if Ruby did tail-call optimization (TCO).
* [[MRI]] does not do TCO; so this function fails with a long list (by overflowing the call stack).
<langsyntaxhighlight lang="ruby">def eq_indices(list)
result = []
list.empty? and return result
Line 2,393 ⟶ 2,819:
helper.call(left + current, new, right - new, index + 1)
end
helper.call 0, list.first, list.drop(1).inject(:+)sum, 0
result
end</langsyntaxhighlight>
;Imperative Style (faster)
<langsyntaxhighlight lang="ruby">def eq_indices(list)
left, right = 0, list.inject(0, :+)sum
equilibrium_indices = []
Line 2,408 ⟶ 2,834:
equilibrium_indices
end</langsyntaxhighlight>
 
;Test
<langsyntaxhighlight lang="ruby">indices = [
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
Line 2,419 ⟶ 2,845:
indices.each do |x|
puts "%p => %p" % [x, eq_indices(x)]
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,426 ⟶ 2,852:
[2, 9, 2] => [1]
[1, -1, 1, -1, 1, -1, 1] => [0, 1, 2, 3, 4, 5, 6]
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
extern crate num;
 
use num::traits::Zero;
 
fn equilibrium_indices(v: &[i32]) -> Vec<usize> {
let mut right = v.iter().sum();
let mut left = i32::zero();
 
v.iter().enumerate().fold(vec![], |mut out, (i, &el)| {
right -= el;
if left == right {
out.push(i);
}
left += el;
 
out
})
}
 
fn main() {
let v = [-7i32, 1, 5, 2, -4, 3, 0];
let indices = equilibrium_indices(&v);
println!("Equilibrium indices for {:?} are: {:?}", v, indices);
}
</syntaxhighlight>
{{out}}
<pre>
Equilibrium indices for [-7, 1, 5, 2, -4, 3, 0] are: [3, 6]
</pre>
 
=={{header|Scala}}==
 
<langsyntaxhighlight Scalalang="scala"> def getEquilibriumIndex(A: Array[Int]): Int = {
val bigA: Array[BigInt] = A.map(BigInt(_))
val partialSums: Array[BigInt] = bigA.scanLeft(BigInt(0))(_+_).tail
Line 2,437 ⟶ 2,895:
def isRandLSumEqual(i: Int): Boolean = lSum(i) == rSum(i)
(0 until partialSums.length).find(isRandLSumEqual).getOrElse(-1)
} </langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const array integer: numList is [] (-7, 1, 5, 2, -4, 3, 0);
Line 2,479 ⟶ 2,937:
end for;
writeln;
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,486 ⟶ 2,944:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func eq_index(nums) {
var (i, sum, sums) = (0, 0, Hash.new);
nums.each { |n|
Line 2,493 ⟶ 2,951:
}
sums{sum} \\ [];
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="ruby">var indices = [
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
Line 2,505 ⟶ 2,963:
for x in indices {
say ("%s => %s" % @|[x, eq_index(x)].map{.dump});
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,516 ⟶ 2,974:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension Collection where Element: Numeric {
func equilibriumIndexes() -> [Index] {
guard !isEmpty else {
Line 2,543 ⟶ 3,001:
let arr = [-7, 1, 5, 2, -4, 3, 0]
 
print("Equilibrium indexes of \(arr): \(arr.equilibriumIndexes())")</langsyntaxhighlight>
 
{{out}}
Line 2,550 ⟶ 3,008:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc listEquilibria {list} {
set after 0
foreach item $list {incr after $item}
Line 2,565 ⟶ 3,023:
}
return $result
}</langsyntaxhighlight>
;Example of use
<langsyntaxhighlight lang="tcl">set testData {-7 1 5 2 -4 3 0}
puts Equilibria=[join [listEquilibria $testData] ", "]</langsyntaxhighlight>
{{out}}
<pre>Equilibria=3, 6</pre>
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import int
 
Line 2,580 ⟶ 3,038:
#cast %nL
 
example = edex <-7,1,5,2,-4,3,0></langsyntaxhighlight>
{{out}}
<pre>
Line 2,588 ⟶ 3,046:
=={{header|VBScript}}==
Solution adopted from http://www.geeksforgeeks.org/equilibrium-index-of-an-array/ .
<langsyntaxhighlight lang="vb">arr = Array(-7,1,5,2,-4,3,0)
WScript.StdOut.Write equilibrium(arr,UBound(arr))
WScript.StdOut.WriteLine
Line 2,606 ⟶ 3,064:
leftsum = leftsum + arr(i)
Next
End Function</langsyntaxhighlight>
 
{{out}}
<pre>Indices: 3, 6,</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">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))
}</syntaxhighlight>
 
{{out}}
<pre>
The equilibrium indices for the following sequences are:
 
[-7, 1, 5, 2, -4, 3, 0] -> [3, 6]
[2, 4, 6] -> []
[2, 9, 2] -> [1]
[1, -1, 1, -1, 1, -1, 1] -> [0, 1, 2, 3, 4, 5, 6]
[1] -> [0]
[] -> []
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Ran=1, ChOut=8, IntOut=11;
def Size = 1_000_000;
int I, S, A(Size), Hi(Size), Lo(Size);
Line 2,622 ⟶ 3,124:
for I:= 0 to Size-1 do
if Lo(I) = Hi(I) then [IntOut(0, I); ChOut(0, ^ )];
]</langsyntaxhighlight>
 
{{out}}
Line 2,631 ⟶ 3,133:
=={{header|Yorick}}==
Yorick arrays are 1-based so the output of this program will be shifted up by one compared to solutions in languages with 0-based arrays.
<langsyntaxhighlight lang="yorick">func equilibrium_indices(A) {
return where(A(psum) == A(::-1)(psum)(::-1));
}</langsyntaxhighlight>
{{out|Example interactive usage}}
<pre>> equilibrium_indices([-7, 1, 5, 2, -4, 3, 0])
Line 2,640 ⟶ 3,142:
=={{header|zkl}}==
{{trans|Clojure}}
<langsyntaxhighlight lang="zkl">fcn equilibrium(lst){ // two pass
reg acc=List(), left=0,right=lst.sum(0),i=0;
foreach x in (lst){
Line 2,648 ⟶ 3,150:
}
acc
}</langsyntaxhighlight>
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn equilibrium(lst){ // lst should immutable, n^2
(0).filter(lst.len(),'wrap(n){ lst[0,n].sum(0) == lst[n+1,*].sum(0) })
}</langsyntaxhighlight>
If the input list is immutable, no new lists are generated (other than accumulating the result).
<langsyntaxhighlight lang="zkl">equilibrium(T(-7, 1, 5, 2, -4, 3, 0)).println();</langsyntaxhighlight>
{{out}}
<pre>L(3,6)</pre>
Line 2,660 ⟶ 3,162:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<langsyntaxhighlight lang="zxbasic">10 DATA 7,-7,1,5,2,-4,3,0
20 READ n
30 DIM a(n): LET sum=0: LET leftsum=0: LET s$=""
Line 2,671 ⟶ 3,173:
100 PRINT "Numbers: ";
110 FOR i=1 TO n: PRINT a(i);" ";: NEXT i
120 PRINT '"Indices: ";s$</langsyntaxhighlight>
1,978

edits