Equilibrium index: Difference between revisions

Added Easylang
(Added Easylang)
 
(22 intermediate revisions by 12 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!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Line 119:
Test(c,9)
Test(d,1)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Equilibrium_index.png Screenshot from Atari 8-bit computer]
Line 141:
 
equilibrium.ads:
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Vectors;
 
generic
Line 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 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 232:
end loop;
Ada.Text_IO.New_Line;
end Main;</langsyntaxhighlight>
{{out}}
(Index_Type is based on 1):
Line 243:
{{works with|Ada 2005}}
equilibrium.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Equilibrium is
Line 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 327:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">list
eqindex(list l)
{
Line 351:
 
0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 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 382:
# OD # );
print(new line)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 389:
 
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}(ES6 version)
<langsyntaxhighlight lang="applescript">-- equilibriumIndices :: [Int] -> [Int]
on equilibriumIndices(xs)
Line 567 ⟶ 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}}==
 
<langsyntaxhighlight lang="rebol">eqIndex: function [row][
suml: 0
delayed: 0
Line 595 ⟶ 624:
 
loop data 'd ->
print [pad.right join.with:", " to [:string] d 25 "=> equilibrium index:" eqIndex d]</langsyntaxhighlight>
 
{{out}}
Line 605 ⟶ 634:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Equilibrium_index(list, BaseIndex=0){
StringSplit, A, list, `,
Loop % A0 {
Line 618 ⟶ 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 653 ⟶ 682:
return(str)
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
Line 668 ⟶ 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 711 ⟶ 765:
echo [!equilms!]
goto :EOF
%==/The Function ==%</langsyntaxhighlight>
{{Out}}
<pre>[3 6]
Line 720 ⟶ 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 732 ⟶ 786:
r += l(i%)
NEXT
= LEFT$(e$)</langsyntaxhighlight>
'''Output:'''
<pre>
Line 739 ⟶ 793:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 782 ⟶ 836:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 815 ⟶ 869:
}
}
}</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">3
6</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <numeric>
Line 860 ⟶ 914:
 
std::for_each(indices.begin(), indices.end(), print<size_t>);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 869 ⟶ 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 876 ⟶ 930:
right (- right x)
acc (if (= left right) (cons i acc) acc)]
(recur acc (inc i) (+ left x) right xs)))))</langsyntaxhighlight>
{{out}}
<pre>
Line 884 ⟶ 938:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun dflt-on-nil (v dflt)
(if v v dflt))
 
Line 898 ⟶ 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 913 ⟶ 967:
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[3, 6]</pre>
Line 920 ⟶ 974:
{{trans|PHP}}
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
size_t[] equilibrium(T)(in T[] items) @safe pure nothrow {
Line 937 ⟶ 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 974 ⟶ 1,050:
while(en.next())
{
var element := *en.get();
right -= element;
bool found := (left == right);
Line 1,001 ⟶ 1,077:
}
get Value() = index;
enumerable() => en;
Line 1,009 ⟶ 1,085:
{
EquilibriumEnumerator.new(new int[]{ -7, 1, 5, 2, -4, 3, 0 })
.forEach:(printingLn)
}</langsyntaxhighlight>
<pre>
3
Line 1,019 ⟶ 1,095:
{{trans|Ruby}}
computes either side each time.
<langsyntaxhighlight lang="elixir">defmodule Equilibrium do
def index(list) do
last = length(list)
Line 1,026 ⟶ 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 1,035 ⟶ 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 1,046 ⟶ 1,122:
Enum.each(indices, fn list ->
IO.puts "#{inspect list} => #{inspect Equilibrium.index(list)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 1,057 ⟶ 1,133:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM EQUILIBRIUM
 
Line 1,079 ⟶ 1,155:
PRINT("Equilibrium indices are";RES$)
END PROGRAM
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,086 ⟶ 1,162:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function equilibrium(sequence s)
integer lower_sum, higher_sum
sequence indices
Line 1,105 ⟶ 1,181:
end function
 
? equilibrium({-7,1,5,2,-4,3,0})</langsyntaxhighlight>
{{out}}
''(Remember that indices are 1-based in Euphoria)''
Line 1,112 ⟶ 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,143 ⟶ 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,181 ⟶ 1,257:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,191 ⟶ 1,267:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Equilibrium_index}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. 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 storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Equilibrium index 01.png]]
In '''[https://formulae.org/?example=Equilibrium_index this]''' page you can see the program(s) related to this task and their results.
 
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,233 ⟶ 1,329:
}
return
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,241 ⟶ 1,337:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Random (randomRIO)
import Data.List (findIndices, takeWhile)
import Control.Monad (replicateM)
Line 1,250 ⟶ 1,346:
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
Line 1,281 ⟶ 1,377:
[1],
[]
]</langsyntaxhighlight>
{{Out}}
<pre>[3,6]
Line 1,291 ⟶ 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,306 ⟶ 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,342 ⟶ 1,438:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,352 ⟶ 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,370 ⟶ 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,392 ⟶ 1,488:
return -1;
}
</syntaxhighlight>
</lang>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">3, -1, 1, 0, 0</langsyntaxhighlight>
 
===ES6 Functional===
Line 1,400 ⟶ 1,496:
A composition of pure generic functions, returning '''all''' equilibrium indices.
 
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 1,508 ⟶ 1,604:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[3,6]
Line 1,518 ⟶ 1,614:
 
=={{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,548 ⟶ 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,561 ⟶ 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,577 ⟶ 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,585 ⟶ 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,597 ⟶ 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,624 ⟶ 1,712:
else -> println("The equilibrium indices are : ${ei.joinToString(", ")}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,632 ⟶ 1,720:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
a(0)=-7
a(1)=1
Line 1,659 ⟶ 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,673 ⟶ 1,761:
end
 
show equilibrium_index [-7 1 5 2 -4 3 0] ; [4 7]</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function array_sum(t)
assert(type(t) == "table", "t must be a table!")
Line 1,700 ⟶ 1,788:
print(equilibrium_index({-7, 1, 5, 2, -4, 3, 0}))
 
</syntaxhighlight>
</lang>
=={{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,712 ⟶ 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,722 ⟶ 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,769 ⟶ 1,857:
return
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,781 ⟶ 1,869:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import math, sequtils, strutils
iterator eqindex(data: openArray[int]): int =
Line 1,800 ⟶ 1,888:
for data in d:
echo "d = [", data.join(", "), ']'
echo "eqIndex(d) -> [", toSeq(eqindex(data)).join(", "), ']'</langsyntaxhighlight>
 
{{out}}
Line 1,814 ⟶ 1,902:
=={{header|Objeck}}==
{{Trans|Java}}
<langsyntaxhighlight lang="objeck">class Rosetta {
function : Main(args : String[]) ~ Nil {
sequence := [-7, 1, 5, 2, -4, 3, 0];
Line 1,837 ⟶ 1,925:
};
}
}</langsyntaxhighlight>
 
Output:
Line 1,846 ⟶ 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,860 ⟶ 1,948:
print_string "Results:";
List.iter (Printf.printf " %d") res;
print_newline ()</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,866 ⟶ 1,954:
Oforth collections are 1-based
 
<langsyntaxhighlight Oforthlang="oforth">: equilibrium(l)
| ls rs i e |
0 ->ls
Line 1,874 ⟶ 1,962:
rs e - dup ->rs ls == ifTrue: [ i over add ]
ls e + ->ls
] ;</langsyntaxhighlight>
 
{{out}}
Line 1,884 ⟶ 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,892 ⟶ 1,980:
);
if(b,u,concat(u,#v))
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program EquilibriumIndexDemo(output);
 
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
Line 1,930 ⟶ 2,018:
EquilibriumIndex(numbers, low(numbers));
writeln;
end.</langsyntaxhighlight>
{{out}}
<pre>:> ./EquilibriumIndex
Line 1,939 ⟶ 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 2,024 ⟶ 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 2,032 ⟶ 2,120:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">sub eq_index {
my ( $i, $sum, %sums ) = ( 0, 0 );
 
Line 2,046 ⟶ 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}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 2,066 ⟶ 2,154:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
(Remember that indices are 1-based in Phix)
Line 2,074 ⟶ 2,162:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$arr = array(-7, 1, 5, 2, -4, 3, 0);
 
Line 2,091 ⟶ 2,179:
echo "# results:\n";
foreach (getEquilibriums($arr) as $r) echo "$r, ";
?></langsyntaxhighlight>
{{out}}
<pre>
Line 2,100 ⟶ 2,188:
=={{header|Picat}}==
Note: Picat is 1-based.
 
<lang Picat>go =>
===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
Line 2,131 ⟶ 2,244:
println(r2=R2),
 
nl.</syntaxhighlight>
% Inspired by the Prolog solution
equilibrium_index1(A, Ix) =>
append(Front, [_|Back], A),
sum(Front) = sum(Back),
Ix = length(Front)+1. % give 1 based index
 
{{out}}
% From the Java solution
<pre>a = [-7,1,5,2,-4,3,0]
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.
 
</lang>
 
Output:
<pre>
a = [-7,1,5,2,-4,3,0]
all1 = [4,7]
all2 = [4,7]
Line 2,186 ⟶ 2,275:
CPU time 0.019 seconds.
 
r2 = [115,372,4082,4254,4258,4261]</pre>
</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 2,206 ⟶ 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 2,229 ⟶ 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 2,241 ⟶ 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,270 ⟶ 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,279 ⟶ 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,287 ⟶ 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,311 ⟶ 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,322 ⟶ 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,346 ⟶ 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,410 ⟶ 2,498:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Equilibrium indices:
Line 2,420 ⟶ 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,438 ⟶ 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,457 ⟶ 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,476 ⟶ 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,488 ⟶ 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,506 ⟶ 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,519 ⟶ 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}}==
<langsyntaxhighlight ReScriptlang="rescript">let arr = [-7, 1, 5, 2, -4, 3, 0]
let sum = Js.Array2.reduce(arr, \"+", 0)
let len = Js.Array.length(arr)
Line 2,540 ⟶ 2,649:
let res = aux([], 0, 0, sum)
Js.log("Results:")
Js.Array2.forEach(res, Js.log)</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,546 ⟶ 2,655:
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.*/
Line 2,562 ⟶ 2,671:
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>
Line 2,589 ⟶ 2,698:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 30.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 2,621 ⟶ 2,730:
eil=eil im1
End
Return eil</langsyntaxhighlight>
'''output'''
<pre> array list: -7 1 5 2 -4 3 0
Line 2,637 ⟶ 2,746:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
list = [-7, 1, 5, 2, -4, 3, 0]
see "equilibrium indices are : " + equilibrium(list) + nl
Line 2,652 ⟶ 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>
 
Line 2,661 ⟶ 2,800:
 
;Functional Style
<langsyntaxhighlight lang="ruby">def eq_indices(list)
list.each_index.select do |i|
list[0...i].sum == list[i+1..-1].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,682 ⟶ 2,821:
helper.call 0, list.first, list.drop(1).sum, 0
result
end</langsyntaxhighlight>
;Imperative Style (faster)
<langsyntaxhighlight lang="ruby">def eq_indices(list)
left, right = 0, list.sum
equilibrium_indices = []
Line 2,695 ⟶ 2,834:
equilibrium_indices
end</langsyntaxhighlight>
 
;Test
<langsyntaxhighlight lang="ruby">indices = [
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
Line 2,706 ⟶ 2,845:
indices.each do |x|
puts "%p => %p" % [x, eq_indices(x)]
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,716 ⟶ 2,855:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
extern crate num;
 
Line 2,741 ⟶ 2,880:
println!("Equilibrium indices for {:?} are: {:?}", v, indices);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,749 ⟶ 2,888:
=={{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,756 ⟶ 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,798 ⟶ 2,937:
end for;
writeln;
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,805 ⟶ 2,944:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func eq_index(nums) {
var (i, sum, sums) = (0, 0, Hash.new);
nums.each { |n|
Line 2,812 ⟶ 2,951:
}
sums{sum} \\ [];
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="ruby">var indices = [
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
Line 2,824 ⟶ 2,963:
for x in indices {
say ("%s => %s" % @|[x, eq_index(x)].map{.dump});
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,835 ⟶ 2,974:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension Collection where Element: Numeric {
func equilibriumIndexes() -> [Index] {
guard !isEmpty else {
Line 2,862 ⟶ 3,001:
let arr = [-7, 1, 5, 2, -4, 3, 0]
 
print("Equilibrium indexes of \(arr): \(arr.equilibriumIndexes())")</langsyntaxhighlight>
 
{{out}}
Line 2,869 ⟶ 3,008:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc listEquilibria {list} {
set after 0
foreach item $list {incr after $item}
Line 2,884 ⟶ 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,899 ⟶ 3,038:
#cast %nL
 
example = edex <-7,1,5,2,-4,3,0></langsyntaxhighlight>
{{out}}
<pre>
Line 2,907 ⟶ 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,925 ⟶ 3,064:
leftsum = leftsum + arr(i)
Next
End Function</langsyntaxhighlight>
 
{{out}}
Line 2,932 ⟶ 3,071:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var equilibrium = Fn.new { |a|
Line 2,959 ⟶ 3,098:
System.print("The equilibrium indices for the following sequences are:\n")
for (test in tests) {
SystemFmt.print("%(Fmt.s(24$24n -> $n", test)), -> %(equilibrium.call(test))")
}</langsyntaxhighlight>
 
{{out}}
Line 2,975 ⟶ 3,114:
 
=={{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,985 ⟶ 3,124:
for I:= 0 to Size-1 do
if Lo(I) = Hi(I) then [IntOut(0, I); ChOut(0, ^ )];
]</langsyntaxhighlight>
 
{{out}}
Line 2,994 ⟶ 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 3,003 ⟶ 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 3,011 ⟶ 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 3,023 ⟶ 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 3,034 ⟶ 3,173:
100 PRINT "Numbers: ";
110 FOR i=1 TO n: PRINT a(i);" ";: NEXT i
120 PRINT '"Indices: ";s$</langsyntaxhighlight>
1,969

edits