Equilibrium index: Difference between revisions
Added Easylang
m (→ES6 Functional) |
(Added Easylang) |
||
(46 intermediate revisions by 23 users not shown) | |||
Line 35:
=={{header|11l}}==
{{trans|Python}}
<
R (0 .< arr.len).filter(i -> sum(@arr[0.<i]) == sum(@arr[i+1..]))
print(eqindex([-7, 1, 5, 2, -4, 3, 0]))</
{{out}}
Line 44:
=={{header|ABAP}}==
<
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 ) ).</
=={{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:
<
generic
Line 81 ⟶ 158:
function Get_Indices (From : Array_Type) return Index_Vectors.Vector;
end Equilibrium;</
equilibrium.adb:
<
function Get_Indices (From : Array_Type) return Index_Vectors.Vector is
Line 102 ⟶ 179:
end Get_Indices;
end Equilibrium;</
Test program using two different versions, one with vectors and one with arrays:
<
with Equilibrium;
with Ada.Containers.Vectors;
Line 155 ⟶ 232:
end loop;
Ada.Text_IO.New_Line;
end Main;</
{{out}}
(Index_Type is based on 1):
Line 166 ⟶ 243:
{{works with|Ada 2005}}
equilibrium.adb:
<
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;</
{{out}}
<pre>Results:
Line 250 ⟶ 327:
=={{header|Aime}}==
<
eqindex(list l)
{
Line 274 ⟶ 351:
0;
}</
=={{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]}}
<
PROC gen equilibrium index = ([]INT arr, YIELDINT yield)VOID:
Line 305 ⟶ 382:
# OD # );
print(new line)
)</
{{out}}
<pre>
Line 312 ⟶ 389:
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}(ES6 version)
<
on equilibriumIndices(xs)
Line 490 ⟶ 568:
end repeat
return lst
end zip</
{{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}}==
<
StringSplit, A, list, `,
Loop % A0 {
Line 508 ⟶ 647:
}
return Res
}</
Examples:<
MsgBox % Equilibrium_index(list)</
{{out}}
<pre>3, 6</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f EQUILIBRIUM_INDEX.AWK
BEGIN {
Line 543 ⟶ 682:
return(str)
}
</syntaxhighlight>
<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}}==
<
setlocal enabledelayedexpansion
Line 601 ⟶ 765:
echo [!equilms!]
goto :EOF
%==/The Function ==%</
{{Out}}
<pre>[3 6]
Line 610 ⟶ 774:
=={{header|BBC BASIC}}==
BBC BASIC's '''SUM''' function is useful for this task.
<
list() = -7, 1, 5, 2, -4, 3, 0
PRINT "Equilibrium indices are " FNequilibrium(list())
Line 622 ⟶ 786:
r += l(i%)
NEXT
= LEFT$(e$)</
'''Output:'''
<pre>
Line 629 ⟶ 793:
=={{header|C}}==
<
#include <stdlib.h>
Line 672 ⟶ 836:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 705 ⟶ 869:
}
}
}</
{{out}}
<syntaxhighlight lang="text">3
6</
=={{header|C++}}==
<
#include <iostream>
#include <numeric>
Line 750 ⟶ 914:
std::for_each(indices.begin(), indices.end(), print<size_t>);
}</
{{out}}
<pre>
Line 759 ⟶ 923:
=={{header|Clojure}}==
{{trans|Ocaml}}
<
(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)))))</
{{out}}
<pre>
Line 774 ⟶ 938:
=={{header|Common Lisp}}==
<
(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)))))</
{{out}}
<syntaxhighlight lang="text">(eq-index '(-7 1 5 2 -4 3 0))
(3 6)</
=={{header|D}}==
===More Functional Style===
<
auto equilibrium(Range)(Range r) pure nothrow @safe /*@nogc*/ {
Line 803 ⟶ 967:
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}</
{{out}}
<pre>[3, 6]</pre>
Line 810 ⟶ 974:
{{trans|PHP}}
Same output.
<
size_t[] equilibrium(T)(in T[] items) @safe pure nothrow {
Line 827 ⟶ 991:
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}</
=={{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
<
import system'routines;
import system'collections;
Line 862 ⟶ 1,050:
while(en.next())
{
var element := *en
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
}</
<pre>
3
Line 907 ⟶ 1,095:
{{trans|Ruby}}
computes either side each time.
<
def index(list) do
last = length(list)
Line 914 ⟶ 1,102:
end)
end
end</
faster version:
<
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</
'''Test:'''
<
[-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)</
{{out}}
Line 945 ⟶ 1,133:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM EQUILIBRIUM
Line 967 ⟶ 1,155:
PRINT("Equilibrium indices are";RES$)
END PROGRAM
</syntaxhighlight>
'''Output:'''
<pre>
Line 974 ⟶ 1,162:
=={{header|Euphoria}}==
<
integer lower_sum, higher_sum
sequence indices
Line 993 ⟶ 1,181:
end function
? equilibrium({-7,1,5,2,-4,3,0})</
{{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.
<
: 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 ;</
{{out}}
<
V{ 3 6 }</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Array indices are 1-based.
<
implicit none
Line 1,031 ⟶ 1,219:
end subroutine
end program</
=={{header|FreeBASIC}}==
<
Sub equilibriumIndices (a() As Integer, b() As Integer)
Line 1,069 ⟶ 1,257:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,079 ⟶ 1,267:
=={{header|Fōrmulæ}}==
'''Solution'''
[[File:Fōrmulæ - Equilibrium index 01.png]]
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}}==
<
import (
Line 1,121 ⟶ 1,329:
}
return
}</
{{out}}
<pre>
Line 1,129 ⟶ 1,337:
=={{header|Haskell}}==
<
import Data.List (
import Control.Monad (replicateM)
import Control.Arrow ((&&&))
equilibr xs =
findIndices (\(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</
Small example
<
[3,6]</
Long random list in langeSliert (several tries for this one)
<
[231,245,259,265,382,1480,1611,1612]</
Or, using default Prelude functions:
<
equilibriumIndices xs =
zip3
(scanl1 (+) xs) --
(scanr1 (+) xs) --
[0 ..] -- Indices
>>= (\(x, y, i) -> [i | x == y])
--------------------------- TEST
main :: IO ()
main =
mapM_
print
$ equilibriumIndices
<$> [ [-7, 1, 5, 2, -4, 3, 0],
]
{{Out}}
<pre>[3,6]
Line 1,186 ⟶ 1,387:
=={{header|Icon}} and {{header|Unicon}}==
<
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</
{{out}}
<pre>equilibrium indicies of [ -7 1 5 2 -4 3 0 ] = 4 7</pre>
=={{header|J}}==
<
{{out|Example use}}
<
3 6</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
public class Equlibrium {
public static void main(String[] args) {
Line 1,237 ⟶ 1,438:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,247 ⟶ 1,448:
===ES5===
<
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))
});</
{{Out}}
<
===ES6 Procedural===
Two pass O(n), returning only the first equilibrium index.
<
let sum = arr.reduce((a, b) => a + b);
let leftSum = 0;
Line 1,287 ⟶ 1,488:
return -1;
}
</syntaxhighlight>
{{Out}}
<
===ES6 Functional===
A composition of pure generic functions, returning '''all''' equilibrium indices.
<
// ------------- ALL EQUILIBRIUM INDICES -------------
// equilibriumIndices :: [Int] -> [Int]
const equilibriumIndices = xs =>
zip
scanl1(add)(xs)
)(
scanr1(add)(xs)
)
(a, xy, i) => xy[0] === xy[1] ? (
[i, ...a]
) : a, []
);
// ---------------------- TEST -----------------------
const main = () => [
[-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
Line 1,316 ⟶ 1,523:
[1],
[]
].map(
JSON.stringify,
equilibriumIndices
))
.join("\n");
// -> [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []]
// ---------------- GENERIC FUNCTIONS ----------------
// 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 =>
//
//
const v = f(a[0])(x);
}, [startValue, [startValue]])[1];
// scanl1 :: (a -> a -> a) -> [a] -> [a]
const scanl1 = f =>
// scanl1 is a variant of scanl that has no
//
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) =>
// MAIN ---
return main();
})();</
{{Out}}
<pre>
[]
[1]
[0,1,2,3,4,5,6]
[0]
[]</pre>
=={{header|jq}}==
{{works with | jq}}
''Also works with gojq, the Go implementation of jq, and jaq''
`equilibrium_indices` is defined as a 0-arity filter that emits answers as a stream, as is idiomatic in jq.
<syntaxhighlight lang="jq"># The index origin is 0 in jq.
def equilibrium_indices:
. as $in
| add as $add
| foreach
$in[$i] as
if .[0]
</syntaxhighlight>
'''Example 1:'''
<
{{out}}
$ jq -M -n -f equilibrium_indices.jq
Line 1,422 ⟶ 1,636:
6
'''Example 2:'''
<
# Create an array of length n with "init" elements:
def array(n;init): reduce range(0;n) as $i ([]; . + [0]);
count( array(
{{out}}
$ jq -M -n -f equilibrium_indices.jq
Line 1,435 ⟶ 1,649:
{{works with|Julia|0.6}}
<
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])</
{{out}}
Line 1,459 ⟶ 1,673:
=={{header|K}}==
<
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</
=={{header|Kotlin}}==
<
fun equilibriumIndices(a: IntArray): MutableList<Int> {
Line 1,498 ⟶ 1,712:
else -> println("The equilibrium indices are : ${ei.joinToString(", ")}")
}
}</
{{out}}
Line 1,506 ⟶ 1,720:
=={{header|Liberty BASIC}}==
<syntaxhighlight 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>
{{out}}
<pre>EQ Indices are 3, 6 </pre>
=={{header|Logo}}==
<
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]</
=={{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.
<
Do[If[Total[data[[;; n - 1]]] == Total[data[[n + 1 ;;]]],Sow[n]],
{n, Length[data]}]][[2, 1]]</
{{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.
<
indicies = [];
Line 1,570 ⟶ 1,810:
end
end</
{{out}}
<
ans =
4 7</
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref symbols nobinary
Line 1,617 ⟶ 1,857:
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,629 ⟶ 1,869:
=={{header|Nim}}==
{{trans|Python}}
<
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(", "), ']'</
{{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}}
<
function : Main(args : String[]) ~ Nil {
sequence := [-7, 1, 5, 2, -4, 3, 0];
Line 1,675 ⟶ 1,925:
};
}
}</
Output:
Line 1,684 ⟶ 1,934:
=={{header|OCaml}}==
<
let sum = List.fold_left ( + ) 0 lst
Line 1,698 ⟶ 1,948:
print_string "Results:";
List.iter (Printf.printf " %d") res;
print_newline ()</
=={{header|Oforth}}==
Line 1,704 ⟶ 1,954:
Oforth collections are 1-based
<
| ls rs i e |
0 ->ls
Line 1,712 ⟶ 1,962:
rs e - dup ->rs ls == ifTrue: [ i over add ]
ls e + ->ls
] ;</
{{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.
<
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))
};</
=={{header|Pascal}}==
<
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
function ArraySum(list: array of integer; first, last: integer): integer;
Line 1,739 ⟶ 1,991:
i: integer;
begin
for i := first to last do // not taken if first > last
end;
Line 1,766 ⟶ 2,018:
EquilibriumIndex(numbers, low(numbers));
writeln;
end.</
{{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.
<
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
type
Line 1,860 ⟶ 2,112:
numbers[i]:= 0;
TestRun(numbers);
end.</
Equilibirum indices: 3 6
Line 1,868 ⟶ 2,120:
=={{header|Perl}}==
{{trans|Raku}}
<
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</
=={{header|Phix}}==
<!--<syntaxhighlight lang="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>
<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>
<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>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<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>
<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>
<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>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<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}}==
<
$arr = array(-7, 1, 5, 2, -4, 3, 0);
Line 1,924 ⟶ 2,179:
echo "# results:\n";
foreach (getEquilibriums($arr) as $r) echo "$r, ";
?></
{{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}}==
<
(make
(let Sum 0
(for ((I . L) Lst L (cdr L))
(and (= Sum (sum prog (cdr L))) (link I))
(inc 'Sum (car L)) ) ) ) )</
{{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">
function Get-EquilibriumIndex ( $Sequence )
{
Line 1,971 ⟶ 2,317:
return $EqulibriumIndex
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
Get-EquilibriumIndex -7, 1, 5, 2, -4, 3, 0
</syntaxhighlight>
{{out}}
<pre>
Line 1,983 ⟶ 2,329:
=={{header|Prolog}}==
<
append(Front, [_|Back], List),
sumlist(Front, Sum),
sumlist(Back, Sum),
length(Front, Len),
Index is Len.</
Example:
<
Index = 3 ;
Index = 6 ;
false.</
=={{header|PureBasic}}==
{{trans|Java}}
<
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</
{{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.
<
"Two pass"
suml, sumr, ddelayed = 0, sum(data), 0
Line 2,029 ⟶ 2,375:
ddelayed = d
if suml == sumr:
yield i</
===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:
<
"Multi pass"
for i in range(len(data)):
suml, sumr = sum(data[:i]), sum(data[i+1:])
if suml == sumr:
yield i</
Shorter alternative:
<
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])</
===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.
<
def eqindex1Pass(data):
Line 2,053 ⟶ 2,399:
l += c
h[l * 2 - c].append(i)
return h[l]</
===Tests===
<
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))))</
{{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:
<
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
'''
ls = list(accumulate(xs))
n = ls[-1]
return [
)) if x == y
]
return go(xs) if xs else []
#
# main :: IO ()
def main():
Line 2,126 ⟶ 2,477:
#
# tabulated :: String -> (a -> b) -> [a] -> String
def tabulated(s):
'''heading -> function -> input List
-> tabulated output string
'''
def go(f):
def width(x):
return len(str(x))
str(x).rjust(w, ' ') + ' -> ' + str(f(x))
])
return cols
return go
if __name__ == '__main__':
main()</
{{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}}==
<
#lang racket
(define (subsums xs)
Line 2,171 ⟶ 2,547:
(equivilibrium '(-7 1 5 2 -4 3 0))
</syntaxhighlight>
{{out}}
<
'(3 6)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
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/);</
And here's an FP solution that manages to remain O(n):
<syntaxhighlight lang="raku"
my @a = [\+] @list;
my @b = reverse [\+] reverse @list;
^@list Zxx (@a »==« @b);
}</
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"
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</
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"
-7 => [ 0, 2 ],
-13 => [ 1 ],
Line 2,221 ⟶ 2,597:
-2 => [ 4 ],
-3 => [ 5 ],
}</
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"
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</
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}}==
<
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>
{{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 ''zero-based'' stemmed array to mimic the illustrative example in this Rosetta Code task's
<br>prologue, which uses a ''zero-based'' index.
<
parse arg x /*obtain the optional arguments from CL*/
if x='' then x= copies(" 7 -7", 50) 7
say ' array list: ' space(x) /*echo the array list to the terminal. */
#= words(x)
do j=0 for #;
end /*j*/ /* [↑] assign @.0 @.1 @.3 ··· */
say /* ··· and also display a blank line. */
answer= equilibriumIDX();
say 'equilibrium' word("(none) index: indices:", 1 + (w>0) + (w>1)) answer
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
equilibriumIDX: $=;
return $ /*return equilibrium list (may be null)*/</
<pre>
array list: -7 1 5 2 -4 3 0
Line 2,282 ⟶ 2,678:
equilibrium indices: 3 6
</pre>
<pre>
array list: 2 9 2
Line 2,288 ⟶ 2,684:
equilibrium index: 1
</pre>
<pre>
array list: 5 4 4 5
Line 2,294 ⟶ 2,690:
equilibrium (none)
</pre>
<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===
<
* 30.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 2,334 ⟶ 2,730:
eil=eil im1
End
Return eil</
'''output'''
<pre> array list: -7 1 5 2 -4 3 0
Line 2,350 ⟶ 2,746:
=={{header|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>
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}}==
;Functional Style
<
list.each_index.select do |i|
list[0...i].
end
end</
;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).
<
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).
result
end</
;Imperative Style (faster)
<
left, right = 0, list.
equilibrium_indices = []
Line 2,408 ⟶ 2,834:
equilibrium_indices
end</
;Test
<
[-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</
{{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}}==
<
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)
} </
=={{header|Seed7}}==
<
const array integer: numList is [] (-7, 1, 5, 2, -4, 3, 0);
Line 2,479 ⟶ 2,937:
end for;
writeln;
end func;</
{{out}}
<pre>
Line 2,486 ⟶ 2,944:
=={{header|Sidef}}==
<
var (i, sum, sums) = (0, 0, Hash.new);
nums.each { |n|
Line 2,493 ⟶ 2,951:
}
sums{sum} \\ [];
}</
Test:
<
[-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});
}</
{{out}}
<pre>
Line 2,516 ⟶ 2,974:
=={{header|Swift}}==
<
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())")</
{{out}}
Line 2,550 ⟶ 3,008:
=={{header|Tcl}}==
<
set after 0
foreach item $list {incr after $item}
Line 2,565 ⟶ 3,023:
}
return $result
}</
;Example of use
<
puts Equilibria=[join [listEquilibria $testData] ", "]</
{{out}}
<pre>Equilibria=3, 6</pre>
=={{header|Ursala}}==
<
#import int
Line 2,580 ⟶ 3,038:
#cast %nL
example = edex <-7,1,5,2,-4,3,0></
{{out}}
<pre>
Line 2,588 ⟶ 3,046:
=={{header|VBScript}}==
Solution adopted from http://www.geeksforgeeks.org/equilibrium-index-of-an-array/ .
<
WScript.StdOut.Write equilibrium(arr,UBound(arr))
WScript.StdOut.WriteLine
Line 2,606 ⟶ 3,064:
leftsum = leftsum + arr(i)
Next
End Function</
{{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}}==
<
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, ^ )];
]</
{{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.
<
return where(A(psum) == A(::-1)(psum)(::-1));
}</
{{out|Example interactive usage}}
<pre>> equilibrium_indices([-7, 1, 5, 2, -4, 3, 0])
Line 2,640 ⟶ 3,142:
=={{header|zkl}}==
{{trans|Clojure}}
<
reg acc=List(), left=0,right=lst.sum(0),i=0;
foreach x in (lst){
Line 2,648 ⟶ 3,150:
}
acc
}</
{{trans|D}}
<
(0).filter(lst.len(),'wrap(n){ lst[0,n].sum(0) == lst[n+1,*].sum(0) })
}</
If the input list is immutable, no new lists are generated (other than accumulating the result).
<
{{out}}
<pre>L(3,6)</pre>
Line 2,660 ⟶ 3,162:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<
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$</
|