Equilibrium index: Difference between revisions
Added Easylang
(Added solution for Action!) |
(Added Easylang) |
||
(27 intermediate revisions by 15 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!}}==
<
INT i
Line 119:
Test(c,9)
Test(d,1)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Equilibrium_index.png Screenshot from Atari 8-bit computer]
Line 141:
equilibrium.ads:
<
generic
Line 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 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 232:
end loop;
Ada.Text_IO.New_Line;
end Main;</
{{out}}
(Index_Type is based on 1):
Line 243:
{{works with|Ada 2005}}
equilibrium.adb:
<
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;</
{{out}}
<pre>Results:
Line 327:
=={{header|Aime}}==
<
eqindex(list l)
{
Line 351:
0;
}</
=={{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]}}
<
PROC gen equilibrium index = ([]INT arr, YIELDINT yield)VOID:
Line 382:
# OD # );
print(new line)
)</
{{out}}
<pre>
Line 389:
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}(ES6 version)
<
on equilibriumIndices(xs)
Line 567 ⟶ 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}}==
<
suml: 0
delayed: 0
Line 595 ⟶ 624:
loop data 'd ->
print [pad.right join.with:", " to [:string] d 25 "=> equilibrium index:" eqIndex d]</
{{out}}
Line 605 ⟶ 634:
=={{header|AutoHotkey}}==
<
StringSplit, A, list, `,
Loop % A0 {
Line 618 ⟶ 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 653 ⟶ 682:
return(str)
}
</syntaxhighlight>
<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}}==
<
setlocal enabledelayedexpansion
Line 711 ⟶ 765:
echo [!equilms!]
goto :EOF
%==/The Function ==%</
{{Out}}
<pre>[3 6]
Line 720 ⟶ 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 732 ⟶ 786:
r += l(i%)
NEXT
= LEFT$(e$)</
'''Output:'''
<pre>
Line 739 ⟶ 793:
=={{header|C}}==
<
#include <stdlib.h>
Line 782 ⟶ 836:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 815 ⟶ 869:
}
}
}</
{{out}}
<syntaxhighlight lang="text">3
6</
=={{header|C++}}==
<
#include <iostream>
#include <numeric>
Line 860 ⟶ 914:
std::for_each(indices.begin(), indices.end(), print<size_t>);
}</
{{out}}
<pre>
Line 869 ⟶ 923:
=={{header|Clojure}}==
{{trans|Ocaml}}
<
(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)))))</
{{out}}
<pre>
Line 884 ⟶ 938:
=={{header|Common Lisp}}==
<
(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)))))</
{{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 913 ⟶ 967:
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}</
{{out}}
<pre>[3, 6]</pre>
Line 920 ⟶ 974:
{{trans|PHP}}
Same output.
<
size_t[] equilibrium(T)(in T[] items) @safe pure nothrow {
Line 937 ⟶ 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 974 ⟶ 1,050:
while(en.next())
{
var element := *en
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
}</
<pre>
3
Line 1,019 ⟶ 1,095:
{{trans|Ruby}}
computes either side each time.
<
def index(list) do
last = length(list)
Line 1,026 ⟶ 1,102:
end)
end
end</
faster version:
<
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</
'''Test:'''
<
[-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)</
{{out}}
Line 1,057 ⟶ 1,133:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM EQUILIBRIUM
Line 1,079 ⟶ 1,155:
PRINT("Equilibrium indices are";RES$)
END PROGRAM
</syntaxhighlight>
'''Output:'''
<pre>
Line 1,086 ⟶ 1,162:
=={{header|Euphoria}}==
<
integer lower_sum, higher_sum
sequence indices
Line 1,105 ⟶ 1,181:
end function
? equilibrium({-7,1,5,2,-4,3,0})</
{{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.
<
: 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,143 ⟶ 1,219:
end subroutine
end program</
=={{header|FreeBASIC}}==
<
Sub equilibriumIndices (a() As Integer, b() As Integer)
Line 1,181 ⟶ 1,257:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,191 ⟶ 1,267:
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Equilibrium_index}}
'''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,233 ⟶ 1,329:
}
return
}</
{{out}}
<pre>
Line 1,241 ⟶ 1,337:
=={{header|Haskell}}==
<
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</
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
Line 1,281 ⟶ 1,377:
[1],
[]
]</
{{Out}}
<pre>[3,6]
Line 1,291 ⟶ 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,306 ⟶ 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,342 ⟶ 1,438:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,352 ⟶ 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,370 ⟶ 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,392 ⟶ 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, []
);
// ----------------------
const main = () =>
[-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
Line 1,421 ⟶ 1,523:
[1],
[]
].map(
JSON.stringify,
equilibriumIndices
))
.join("\n");
// -> [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []]
// ----------------
// add (+) :: Num a => a -> a -> a
Line 1,441 ⟶ 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,472 ⟶ 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,483 ⟶ 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,527 ⟶ 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,540 ⟶ 1,649:
{{works with|Julia|0.6}}
<
rst = Vector{Int}(0)
suml, sumr, ddelayed = 0, sum(data), 0
Line 1,556 ⟶ 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,564 ⟶ 1,673:
=={{header|K}}==
<
f -7 1 5 2 -4 3 0
Line 1,576 ⟶ 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,603 ⟶ 1,712:
else -> println("The equilibrium indices are : ${ei.joinToString(", ")}")
}
}</
{{out}}
Line 1,611 ⟶ 1,720:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
a(0)=-7
a(1)=1
Line 1,638 ⟶ 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,652 ⟶ 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,665 ⟶ 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,675 ⟶ 1,810:
end
end</
{{out}}
<
ans =
4 7</
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref symbols nobinary
Line 1,722 ⟶ 1,857:
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,734 ⟶ 1,869:
=={{header|Nim}}==
{{trans|Python}}
<
iterator eqindex(data: openArray[int]): int =
Line 1,753 ⟶ 1,888:
for data in d:
echo "d = [", data.join(", "), ']'
echo "eqIndex(d) -> [", toSeq(eqindex(data)).join(", "), ']'</
{{out}}
Line 1,767 ⟶ 1,902:
=={{header|Objeck}}==
{{Trans|Java}}
<
function : Main(args : String[]) ~ Nil {
sequence := [-7, 1, 5, 2, -4, 3, 0];
Line 1,790 ⟶ 1,925:
};
}
}</
Output:
Line 1,799 ⟶ 1,934:
=={{header|OCaml}}==
<
let sum = List.fold_left ( + ) 0 lst
Line 1,813 ⟶ 1,948:
print_string "Results:";
List.iter (Printf.printf " %d") res;
print_newline ()</
=={{header|Oforth}}==
Line 1,819 ⟶ 1,954:
Oforth collections are 1-based
<
| ls rs i e |
0 ->ls
Line 1,827 ⟶ 1,962:
rs e - dup ->rs ls == ifTrue: [ i over add ]
ls e + ->ls
] ;</
{{out}}
Line 1,837 ⟶ 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,845 ⟶ 1,980:
);
if(b,u,concat(u,#v))
};</
=={{header|Pascal}}==
<
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
Line 1,883 ⟶ 2,018:
EquilibriumIndex(numbers, low(numbers));
writeln;
end.</
{{out}}
<pre>:> ./EquilibriumIndex
Line 1,892 ⟶ 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,977 ⟶ 2,112:
numbers[i]:= 0;
TestRun(numbers);
end.</
Equilibirum indices: 3 6
Line 1,985 ⟶ 2,120:
=={{header|Perl}}==
{{trans|Raku}}
<
my ( $i, $sum, %sums ) = ( 0, 0 );
Line 1,999 ⟶ 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 2,024 ⟶ 2,162:
=={{header|PHP}}==
<
$arr = array(-7, 1, 5, 2, -4, 3, 0);
Line 2,041 ⟶ 2,179:
echo "# results:\n";
foreach (getEquilibriums($arr) as $r) echo "$r, ";
?></
{{out}}
<pre>
Line 2,047 ⟶ 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 2,065 ⟶ 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 2,088 ⟶ 2,317:
return $EqulibriumIndex
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
Get-EquilibriumIndex -7, 1, 5, 2, -4, 3, 0
</syntaxhighlight>
{{out}}
<pre>
Line 2,100 ⟶ 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,129 ⟶ 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,138 ⟶ 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,146 ⟶ 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,170 ⟶ 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,181 ⟶ 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,205 ⟶ 2,434:
The ''right'' scan can be derived from the left as a map or equivalent list comprehension:
<
from itertools import (accumulate)
Line 2,269 ⟶ 2,498:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Equilibrium indices:
Line 2,279 ⟶ 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,297 ⟶ 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,316 ⟶ 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,335 ⟶ 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,347 ⟶ 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,365 ⟶ 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,378 ⟶ 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}}==
<
let sum = Js.Array2.reduce(arr, \"+", 0)
let len = Js.Array.length(arr)
Line 2,399 ⟶ 2,649:
let res = aux([], 0, 0, sum)
Js.log("Results:")
Js.Array2.forEach(res, Js.log)</
=={{header|REXX}}==
Line 2,405 ⟶ 2,655:
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 /*Not specified? Then use the default.*/
Line 2,421 ⟶ 2,671:
if sum==0 then $= $ i
end /*i*/ /* [↑] Zero? Found an equilibrium index*/
return $ /*return equilibrium list (may be null)*/</
{{out|output|text= when using the input of: <tt> -7 1 5 2 -4 3 0 </tt>}}
<pre>
Line 2,448 ⟶ 2,698:
===version 2===
<
* 30.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 2,480 ⟶ 2,730:
eil=eil im1
End
Return eil</
'''output'''
<pre> array list: -7 1 5 2 -4 3 0
Line 2,496 ⟶ 2,746:
=={{header|Ring}}==
<
list = [-7, 1, 5, 2, -4, 3, 0]
see "equilibrium indices are : " + equilibrium(list) + nl
Line 2,511 ⟶ 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>
Line 2,520 ⟶ 2,800:
;Functional Style
<
list.each_index.select do |i|
list[0...i].sum == list[i+1..-1].sum
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,541 ⟶ 2,821:
helper.call 0, list.first, list.drop(1).sum, 0
result
end</
;Imperative Style (faster)
<
left, right = 0, list.sum
equilibrium_indices = []
Line 2,554 ⟶ 2,834:
equilibrium_indices
end</
;Test
<
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
Line 2,565 ⟶ 2,845:
indices.each do |x|
puts "%p => %p" % [x, eq_indices(x)]
end</
{{out}}
<pre>
Line 2,575 ⟶ 2,855:
=={{header|Rust}}==
<
extern crate num;
Line 2,600 ⟶ 2,880:
println!("Equilibrium indices for {:?} are: {:?}", v, indices);
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,608 ⟶ 2,888:
=={{header|Scala}}==
<
val bigA: Array[BigInt] = A.map(BigInt(_))
val partialSums: Array[BigInt] = bigA.scanLeft(BigInt(0))(_+_).tail
Line 2,615 ⟶ 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,657 ⟶ 2,937:
end for;
writeln;
end func;</
{{out}}
<pre>
Line 2,664 ⟶ 2,944:
=={{header|Sidef}}==
<
var (i, sum, sums) = (0, 0, Hash.new);
nums.each { |n|
Line 2,671 ⟶ 2,951:
}
sums{sum} \\ [];
}</
Test:
<
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
Line 2,683 ⟶ 2,963:
for x in indices {
say ("%s => %s" % @|[x, eq_index(x)].map{.dump});
}</
{{out}}
<pre>
Line 2,694 ⟶ 2,974:
=={{header|Swift}}==
<
func equilibriumIndexes() -> [Index] {
guard !isEmpty else {
Line 2,721 ⟶ 3,001:
let arr = [-7, 1, 5, 2, -4, 3, 0]
print("Equilibrium indexes of \(arr): \(arr.equilibriumIndexes())")</
{{out}}
Line 2,728 ⟶ 3,008:
=={{header|Tcl}}==
<
set after 0
foreach item $list {incr after $item}
Line 2,743 ⟶ 3,023:
}
return $result
}</
;Example of use
<
puts Equilibria=[join [listEquilibria $testData] ", "]</
{{out}}
<pre>Equilibria=3, 6</pre>
=={{header|Ursala}}==
<
#import int
Line 2,758 ⟶ 3,038:
#cast %nL
example = edex <-7,1,5,2,-4,3,0></
{{out}}
<pre>
Line 2,766 ⟶ 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,784 ⟶ 3,064:
leftsum = leftsum + arr(i)
Next
End Function</
{{out}}
Line 2,791 ⟶ 3,071:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<
var equilibrium = Fn.new { |a|
Line 2,818 ⟶ 3,098:
System.print("The equilibrium indices for the following sequences are:\n")
for (test in tests) {
}</
{{out}}
Line 2,834 ⟶ 3,114:
=={{header|XPL0}}==
<
def Size = 1_000_000;
int I, S, A(Size), Hi(Size), Lo(Size);
Line 2,844 ⟶ 3,124:
for I:= 0 to Size-1 do
if Lo(I) = Hi(I) then [IntOut(0, I); ChOut(0, ^ )];
]</
{{out}}
Line 2,853 ⟶ 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,862 ⟶ 3,142:
=={{header|zkl}}==
{{trans|Clojure}}
<
reg acc=List(), left=0,right=lst.sum(0),i=0;
foreach x in (lst){
Line 2,870 ⟶ 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,882 ⟶ 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,893 ⟶ 3,173:
100 PRINT "Numbers: ";
110 FOR i=1 TO n: PRINT a(i);" ";: NEXT i
120 PRINT '"Indices: ";s$</
|