Equilibrium index: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 35: Line 35:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<lang 11l>F eqindex(arr)
<syntaxhighlight lang="11l">F eqindex(arr)
R (0 .< arr.len).filter(i -> sum(@arr[0.<i]) == sum(@arr[i+1..]))
R (0 .< arr.len).filter(i -> sum(@arr[0.<i]) == sum(@arr[i+1..]))


print(eqindex([-7, 1, 5, 2, -4, 3, 0]))</lang>
print(eqindex([-7, 1, 5, 2, -4, 3, 0]))</syntaxhighlight>


{{out}}
{{out}}
Line 44: Line 44:


=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>REPORT equilibrium_index.
<syntaxhighlight lang="abap">REPORT equilibrium_index.


TYPES: y_i TYPE STANDARD TABLE OF i WITH EMPTY KEY.
TYPES: y_i TYPE STANDARD TABLE OF i WITH EMPTY KEY.
Line 57: Line 57:
LET z = sequences[ i ] IN
LET z = sequences[ i ] IN
NEXT x = COND #( WHEN y = ( total_sum - y - z ) THEN VALUE y_i( BASE x ( i - 1 ) ) ELSE x )
NEXT x = COND #( WHEN y = ( total_sum - y - z ) THEN VALUE y_i( BASE x ( i - 1 ) ) ELSE x )
y = y + z ) ).</lang>
y = y + z ) ).</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC PrintArray(INT ARRAY a INT size)
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
INT i


Line 119: Line 119:
Test(c,9)
Test(c,9)
Test(d,1)
Test(d,1)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Equilibrium_index.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Equilibrium_index.png Screenshot from Atari 8-bit computer]
Line 141: Line 141:


equilibrium.ads:
equilibrium.ads:
<lang Ada>with Ada.Containers.Vectors;
<syntaxhighlight lang="ada">with Ada.Containers.Vectors;


generic
generic
Line 158: Line 158:
function Get_Indices (From : Array_Type) return Index_Vectors.Vector;
function Get_Indices (From : Array_Type) return Index_Vectors.Vector;


end Equilibrium;</lang>
end Equilibrium;</syntaxhighlight>
equilibrium.adb:
equilibrium.adb:
<lang Ada>package body Equilibrium is
<syntaxhighlight lang="ada">package body Equilibrium is


function Get_Indices (From : Array_Type) return Index_Vectors.Vector is
function Get_Indices (From : Array_Type) return Index_Vectors.Vector is
Line 179: Line 179:
end Get_Indices;
end Get_Indices;


end Equilibrium;</lang>
end Equilibrium;</syntaxhighlight>
Test program using two different versions, one with vectors and one with arrays:
Test program using two different versions, one with vectors and one with arrays:
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Equilibrium;
with Equilibrium;
with Ada.Containers.Vectors;
with Ada.Containers.Vectors;
Line 232: Line 232:
end loop;
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.New_Line;
end Main;</lang>
end Main;</syntaxhighlight>
{{out}}
{{out}}
(Index_Type is based on 1):
(Index_Type is based on 1):
Line 243: Line 243:
{{works with|Ada 2005}}
{{works with|Ada 2005}}
equilibrium.adb:
equilibrium.adb:
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Equilibrium is
procedure Equilibrium is
Line 310: Line 310:
Ada.Text_IO.Put_Line ("X4:" & Seq_Img (X4));
Ada.Text_IO.Put_Line ("X4:" & Seq_Img (X4));
Ada.Text_IO.Put_Line ("Eqs:" & Seq_Img (X4_Result));
Ada.Text_IO.Put_Line ("Eqs:" & Seq_Img (X4_Result));
end Equilibrium;</lang>
end Equilibrium;</syntaxhighlight>
{{out}}
{{out}}
<pre>Results:
<pre>Results:
Line 327: Line 327:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>list
<syntaxhighlight lang="aime">list
eqindex(list l)
eqindex(list l)
{
{
Line 351: Line 351:


0;
0;
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 358: 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|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]}}
{{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]}}
<lang algol68>MODE YIELDINT = PROC(INT)VOID;
<syntaxhighlight lang="algol68">MODE YIELDINT = PROC(INT)VOID;


PROC gen equilibrium index = ([]INT arr, YIELDINT yield)VOID:
PROC gen equilibrium index = ([]INT arr, YIELDINT yield)VOID:
Line 382: Line 382:
# OD # );
# OD # );
print(new line)
print(new line)
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 390: Line 390:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{Trans|JavaScript}}(ES6 version)
{{Trans|JavaScript}}(ES6 version)
<lang applescript>-- equilibriumIndices :: [Int] -> [Int]
<syntaxhighlight lang="applescript">-- equilibriumIndices :: [Int] -> [Int]
on equilibriumIndices(xs)
on equilibriumIndices(xs)
Line 567: Line 567:
end repeat
end repeat
return lst
return lst
end zip</lang>
end zip</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{{3, 6}, {}, {1}, {0, 1, 2, 3, 4, 5, 6}, {0}, {}}</pre>
<pre>{{3, 6}, {}, {1}, {0, 1, 2, 3, 4, 5, 6}, {0}, {}}</pre>
Line 573: Line 573:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>eqIndex: function [row][
<syntaxhighlight lang="rebol">eqIndex: function [row][
suml: 0
suml: 0
delayed: 0
delayed: 0
Line 595: Line 595:


loop data 'd ->
loop data 'd ->
print [pad.right join.with:", " to [:string] d 25 "=> equilibrium index:" eqIndex d]</lang>
print [pad.right join.with:", " to [:string] d 25 "=> equilibrium index:" eqIndex d]</syntaxhighlight>


{{out}}
{{out}}
Line 605: Line 605:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Equilibrium_index(list, BaseIndex=0){
<syntaxhighlight lang="autohotkey">Equilibrium_index(list, BaseIndex=0){
StringSplit, A, list, `,
StringSplit, A, list, `,
Loop % A0 {
Loop % A0 {
Line 618: Line 618:
}
}
return Res
return Res
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>list = -7, 1, 5, 2, -4, 3, 0
Examples:<syntaxhighlight lang="autohotkey">list = -7, 1, 5, 2, -4, 3, 0
MsgBox % Equilibrium_index(list)</lang>
MsgBox % Equilibrium_index(list)</syntaxhighlight>
{{out}}
{{out}}
<pre>3, 6</pre>
<pre>3, 6</pre>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f EQUILIBRIUM_INDEX.AWK
# syntax: GAWK -f EQUILIBRIUM_INDEX.AWK
BEGIN {
BEGIN {
Line 653: Line 653:
return(str)
return(str)
}
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<p>Output:</p>
<pre>
<pre>
Line 670: Line 670:


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion


Line 711: Line 711:
echo [!equilms!]
echo [!equilms!]
goto :EOF
goto :EOF
%==/The Function ==%</lang>
%==/The Function ==%</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[3 6]
<pre>[3 6]
Line 720: Line 720:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
BBC BASIC's '''SUM''' function is useful for this task.
BBC BASIC's '''SUM''' function is useful for this task.
<lang bbcbasic> DIM list(6)
<syntaxhighlight lang="bbcbasic"> DIM list(6)
list() = -7, 1, 5, 2, -4, 3, 0
list() = -7, 1, 5, 2, -4, 3, 0
PRINT "Equilibrium indices are " FNequilibrium(list())
PRINT "Equilibrium indices are " FNequilibrium(list())
Line 732: Line 732:
r += l(i%)
r += l(i%)
NEXT
NEXT
= LEFT$(e$)</lang>
= LEFT$(e$)</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 739: Line 739:


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 782: Line 782:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 815: Line 815:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<lang>3
<syntaxhighlight lang="text">3
6</lang>
6</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iostream>
#include <numeric>
#include <numeric>
Line 860: Line 860:


std::for_each(indices.begin(), indices.end(), print<size_t>);
std::for_each(indices.begin(), indices.end(), print<size_t>);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 869: Line 869:
=={{header|Clojure}}==
=={{header|Clojure}}==
{{trans|Ocaml}}
{{trans|Ocaml}}
<lang clojure>(defn equilibrium [lst]
<syntaxhighlight lang="clojure">(defn equilibrium [lst]
(loop [acc '(), i 0, left 0, right (apply + lst), lst lst]
(loop [acc '(), i 0, left 0, right (apply + lst), lst lst]
(if (empty? lst)
(if (empty? lst)
Line 876: Line 876:
right (- right x)
right (- right x)
acc (if (= left right) (cons i acc) acc)]
acc (if (= left right) (cons i acc) acc)]
(recur acc (inc i) (+ left x) right xs)))))</lang>
(recur acc (inc i) (+ left x) right xs)))))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 884: Line 884:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun dflt-on-nil (v dflt)
<syntaxhighlight lang="lisp">(defun dflt-on-nil (v dflt)
(if v v dflt))
(if v v dflt))


Line 898: Line 898:
(if (eql lsum rsum) (push i stack))
(if (eql lsum rsum) (push i stack))
(setf lsum (+ lsum (car rest)))
(setf lsum (+ lsum (car rest)))
(setf rsum (- rsum (dflt-on-nil (cadr rest) 0)))))</lang>
(setf rsum (- rsum (dflt-on-nil (cadr rest) 0)))))</syntaxhighlight>
{{out}}
{{out}}
<lang>(eq-index '(-7 1 5 2 -4 3 0))
<syntaxhighlight lang="text">(eq-index '(-7 1 5 2 -4 3 0))
(3 6)</lang>
(3 6)</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
===More Functional Style===
===More Functional Style===
<lang d>import std.stdio, std.algorithm, std.range, std.functional;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.functional;


auto equilibrium(Range)(Range r) pure nothrow @safe /*@nogc*/ {
auto equilibrium(Range)(Range r) pure nothrow @safe /*@nogc*/ {
Line 913: Line 913:
void main() {
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[3, 6]</pre>
<pre>[3, 6]</pre>
Line 920: Line 920:
{{trans|PHP}}
{{trans|PHP}}
Same output.
Same output.
<lang d>import std.stdio, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.algorithm;


size_t[] equilibrium(T)(in T[] items) @safe pure nothrow {
size_t[] equilibrium(T)(in T[] items) @safe pure nothrow {
Line 937: Line 937:
void main() {
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}</lang>
}</syntaxhighlight>
=={{header|Delphi}}==
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Equilibrium_index#Pascal Pascal].
See [https://rosettacode.org/wiki/Equilibrium_index#Pascal Pascal].
Line 943: Line 943:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'routines;
import system'routines;
import system'collections;
import system'collections;
Line 1,010: Line 1,010:
EquilibriumEnumerator.new(new int[]{ -7, 1, 5, 2, -4, 3, 0 })
EquilibriumEnumerator.new(new int[]{ -7, 1, 5, 2, -4, 3, 0 })
.forEach:printingLn
.forEach:printingLn
}</lang>
}</syntaxhighlight>
<pre>
<pre>
3
3
Line 1,019: Line 1,019:
{{trans|Ruby}}
{{trans|Ruby}}
computes either side each time.
computes either side each time.
<lang elixir>defmodule Equilibrium do
<syntaxhighlight lang="elixir">defmodule Equilibrium do
def index(list) do
def index(list) do
last = length(list)
last = length(list)
Line 1,026: Line 1,026:
end)
end)
end
end
end</lang>
end</syntaxhighlight>


faster version:
faster version:
<lang elixir>defmodule Equilibrium do
<syntaxhighlight lang="elixir">defmodule Equilibrium do
def index(list), do: index(list,0,0,Enum.sum(list),[])
def index(list), do: index(list,0,0,Enum.sum(list),[])
Line 1,035: Line 1,035:
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) 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)
defp index([h|t],i,left,right,acc) , do: index(t,i+1,left+h,right-h,acc)
end</lang>
end</syntaxhighlight>


'''Test:'''
'''Test:'''
<lang elixir>indices = [
<syntaxhighlight lang="elixir">indices = [
[-7, 1, 5, 2,-4, 3, 0],
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
[2, 4, 6],
Line 1,046: Line 1,046:
Enum.each(indices, fn list ->
Enum.each(indices, fn list ->
IO.puts "#{inspect list} => #{inspect Equilibrium.index(list)}"
IO.puts "#{inspect list} => #{inspect Equilibrium.index(list)}"
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,057: Line 1,057:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM EQUILIBRIUM
PROGRAM EQUILIBRIUM


Line 1,079: Line 1,079:
PRINT("Equilibrium indices are";RES$)
PRINT("Equilibrium indices are";RES$)
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 1,086: Line 1,086:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function equilibrium(sequence s)
<syntaxhighlight lang="euphoria">function equilibrium(sequence s)
integer lower_sum, higher_sum
integer lower_sum, higher_sum
sequence indices
sequence indices
Line 1,105: Line 1,105:
end function
end function


? equilibrium({-7,1,5,2,-4,3,0})</lang>
? equilibrium({-7,1,5,2,-4,3,0})</syntaxhighlight>
{{out}}
{{out}}
''(Remember that indices are 1-based in Euphoria)''
''(Remember that indices are 1-based in Euphoria)''
Line 1,112: Line 1,112:
=={{header|Factor}}==
=={{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.
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.
<lang factor>USE: math.vectors
<syntaxhighlight lang="factor">USE: math.vectors
: accum-left ( seq id quot -- seq ) accumulate nip ; inline
: accum-left ( seq id quot -- seq ) accumulate nip ; inline
: accum-right ( seq id quot -- seq ) [ <reversed> ] 2dip accum-left <reversed> ; inline
: accum-right ( seq id quot -- seq ) [ <reversed> ] 2dip accum-left <reversed> ; inline
: equilibrium-indices ( seq -- inds )
: equilibrium-indices ( seq -- inds )
0 [ + ] [ accum-left ] [ accum-right ] 3bi [ = ] 2map
0 [ + ] [ accum-left ] [ accum-right ] 3bi [ = ] 2map
V{ } swap dup length iota [ [ suffix ] curry [ ] if ] 2each ;</lang>
V{ } swap dup length iota [ [ suffix ] curry [ ] if ] 2each ;</syntaxhighlight>
{{out}}
{{out}}
<lang factor>( scratchpad ) { -7 1 5 2 -4 3 0 } equilibrium-indices .
<syntaxhighlight lang="factor">( scratchpad ) { -7 1 5 2 -4 3 0 } equilibrium-indices .
V{ 3 6 }</lang>
V{ 3 6 }</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
Array indices are 1-based.
Array indices are 1-based.
<lang fortran>program Equilibrium
<syntaxhighlight lang="fortran">program Equilibrium
implicit none
implicit none
Line 1,143: Line 1,143:


end subroutine
end subroutine
end program</lang>
end program</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Sub equilibriumIndices (a() As Integer, b() As Integer)
Sub equilibriumIndices (a() As Integer, b() As Integer)
Line 1,181: Line 1,181:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,198: Line 1,198:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,233: Line 1,233:
}
}
return
return
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,241: Line 1,241:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import System.Random (randomRIO)
<syntaxhighlight lang="haskell">import System.Random (randomRIO)
import Data.List (findIndices, takeWhile)
import Data.List (findIndices, takeWhile)
import Control.Monad (replicateM)
import Control.Monad (replicateM)
Line 1,250: Line 1,250:
flip ((&&&) <$> take <*> (drop . pred)) xs <$> [1 ..]
flip ((&&&) <$> take <*> (drop . pred)) xs <$> [1 ..]


langeSliert = replicateM 2000 (randomRIO (-15, 15) :: IO Int) >>= print . equilibr</lang>
langeSliert = replicateM 2000 (randomRIO (-15, 15) :: IO Int) >>= print . equilibr</syntaxhighlight>
Small example
Small example
<lang haskell>*Main> equilibr [-7, 1, 5, 2, -4, 3, 0]
<syntaxhighlight lang="haskell">*Main> equilibr [-7, 1, 5, 2, -4, 3, 0]
[3,6]</lang>
[3,6]</syntaxhighlight>
Long random list in langeSliert (several tries for this one)
Long random list in langeSliert (several tries for this one)
<lang haskell>*Main> langeSliert
<syntaxhighlight lang="haskell">*Main> langeSliert
[231,245,259,265,382,1480,1611,1612]</lang>
[231,245,259,265,382,1480,1611,1612]</syntaxhighlight>




Or, using default Prelude functions:
Or, using default Prelude functions:


<lang haskell>equilibriumIndices :: [Int] -> [Int]
<syntaxhighlight lang="haskell">equilibriumIndices :: [Int] -> [Int]
equilibriumIndices xs =
equilibriumIndices xs =
zip3
zip3
Line 1,281: Line 1,281:
[1],
[1],
[]
[]
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[3,6]
<pre>[3,6]
Line 1,291: Line 1,291:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main(arglist)
<syntaxhighlight lang="icon">procedure main(arglist)
L := if *arglist > 0 then arglist else [-7, 1, 5, 2, -4, 3, 0] # command line args or default
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" )
every writes( "equilibrium indicies of [ " | (!L ||" ") | "] = " | (eqindex(L)||" ") | "\n" )
Line 1,306: Line 1,306:
l +:= L[i] # sum of left side
l +:= L[i] # sum of left side
}
}
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>equilibrium indicies of [ -7 1 5 2 -4 3 0 ] = 4 7</pre>
<pre>equilibrium indicies of [ -7 1 5 2 -4 3 0 ] = 4 7</pre>


=={{header|J}}==
=={{header|J}}==
<lang j>equilidx=: +/\ I.@:= +/\.</lang>
<syntaxhighlight lang="j">equilidx=: +/\ I.@:= +/\.</syntaxhighlight>
{{out|Example use}}
{{out|Example use}}
<lang j> equilidx _7 1 5 2 _4 3 0
<syntaxhighlight lang="j"> equilidx _7 1 5 2 _4 3 0
3 6</lang>
3 6</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>
<syntaxhighlight lang="java5">
public class Equlibrium {
public class Equlibrium {
public static void main(String[] args) {
public static void main(String[] args) {
Line 1,342: Line 1,342:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,352: Line 1,352:


===ES5===
===ES5===
<lang javascript>function equilibrium(a) {
<syntaxhighlight lang="javascript">function equilibrium(a) {
var N = a.length, i, l = [], r = [], e = []
var N = a.length, i, l = [], r = [], e = []
for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i<N; i++)
for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i<N; i++)
Line 1,370: Line 1,370:
].forEach(function(x) {
].forEach(function(x) {
console.log(equilibrium(x))
console.log(equilibrium(x))
});</lang>
});</syntaxhighlight>
{{Out}}
{{Out}}
<lang JavaScript>[[3,6],[],[1],[0,1,2,3,4,5,6],[0],[]]</lang>
<syntaxhighlight lang="javascript">[[3,6],[],[1],[0,1,2,3,4,5,6],[0],[]]</syntaxhighlight>


===ES6 Procedural===
===ES6 Procedural===
Two pass O(n), returning only the first equilibrium index.
Two pass O(n), returning only the first equilibrium index.
<lang JavaScript>function equilibrium(arr) {
<syntaxhighlight lang="javascript">function equilibrium(arr) {
let sum = arr.reduce((a, b) => a + b);
let sum = arr.reduce((a, b) => a + b);
let leftSum = 0;
let leftSum = 0;
Line 1,392: Line 1,392:
return -1;
return -1;
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<lang JavaScript>3, -1, 1, 0, 0</lang>
<syntaxhighlight lang="javascript">3, -1, 1, 0, 0</syntaxhighlight>


===ES6 Functional===
===ES6 Functional===
Line 1,400: Line 1,400:
A composition of pure generic functions, returning '''all''' equilibrium indices.
A composition of pure generic functions, returning '''all''' equilibrium indices.


<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 1,508: Line 1,508:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[3,6]
<pre>[3,6]
Line 1,528: Line 1,528:


The top-level function is defined as a 0-arity filter that emits answers as a stream, as is idiomatic 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.
<syntaxhighlight lang="jq"># The index origin is 0 in jq.
def equilibrium_indices:
def equilibrium_indices:
def indices(a; mx):
def indices(a; mx):
Line 1,540: Line 1,540:
end;
end;
[0, 0, (a|add)] | report;
[0, 0, (a|add)] | report;
. as $in | indices($in; $in|length);</lang>
. as $in | indices($in; $in|length);</syntaxhighlight>
'''Example 1:'''
'''Example 1:'''
<lang jq>[-7, 1, 5, 2, -4, 3, 0] | equilibrium_indices</lang>
<syntaxhighlight lang="jq">[-7, 1, 5, 2, -4, 3, 0] | equilibrium_indices</syntaxhighlight>
{{out}}
{{out}}
$ jq -M -n -f equilibrium_indices.jq
$ jq -M -n -f equilibrium_indices.jq
Line 1,548: Line 1,548:
6
6
'''Example 2:'''
'''Example 2:'''
<lang jq>def count(g): reduce g as $i (0; .+1);
<syntaxhighlight lang="jq">def count(g): reduce g as $i (0; .+1);


# Create an array of length n with "init" elements:
# Create an array of length n with "init" elements:
def array(n;init): reduce range(0;n) as $i ([]; . + [0]);
def array(n;init): reduce range(0;n) as $i ([]; . + [0]);


count( array(1e4;0) | equilibrium_indices )</lang>
count( array(1e4;0) | equilibrium_indices )</syntaxhighlight>
{{out}}
{{out}}
$ jq -M -n -f equilibrium_indices.jq
$ jq -M -n -f equilibrium_indices.jq
Line 1,561: Line 1,561:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>function equindex2pass(data::Array)
<syntaxhighlight lang="julia">function equindex2pass(data::Array)
rst = Vector{Int}(0)
rst = Vector{Int}(0)
suml, sumr, ddelayed = 0, sum(data), 0
suml, sumr, ddelayed = 0, sum(data), 0
Line 1,577: Line 1,577:
@show equindex2pass([1, -1, 1, -1, 1, -1, 1])
@show equindex2pass([1, -1, 1, -1, 1, -1, 1])
@show equindex2pass([1, 2, 2, 1])
@show equindex2pass([1, 2, 2, 1])
@show equindex2pass([-7, 1, 5, 2, -4, 3, 0])</lang>
@show equindex2pass([-7, 1, 5, 2, -4, 3, 0])</syntaxhighlight>


{{out}}
{{out}}
Line 1,585: Line 1,585:


=={{header|K}}==
=={{header|K}}==
<lang K> f:{&{(+/y# x)=+/(y+1)_x}[x]'!#x}
<syntaxhighlight lang="k"> f:{&{(+/y# x)=+/(y+1)_x}[x]'!#x}
f -7 1 5 2 -4 3 0
f -7 1 5 2 -4 3 0
Line 1,597: Line 1,597:
f 1 -1 1 -1 1 -1 1
f 1 -1 1 -1 1 -1 1
0 1 2 3 4 5 6</lang>
0 1 2 3 4 5 6</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1
<syntaxhighlight lang="scala">// version 1.1


fun equilibriumIndices(a: IntArray): MutableList<Int> {
fun equilibriumIndices(a: IntArray): MutableList<Int> {
Line 1,624: Line 1,624:
else -> println("The equilibrium indices are : ${ei.joinToString(", ")}")
else -> println("The equilibrium indices are : ${ei.joinToString(", ")}")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,632: Line 1,632:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
a(0)=-7
a(0)=-7
a(1)=1
a(1)=1
Line 1,659: Line 1,659:
if len(EQindex$)>0 then EQindex$=mid$(EQindex$, 1, len(EQindex$)-2) 'remove last ", "
if len(EQindex$)>0 then EQindex$=mid$(EQindex$, 1, len(EQindex$)-2) 'remove last ", "
end function
end function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>EQ Indices are 3, 6 </pre>
<pre>EQ Indices are 3, 6 </pre>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to equilibrium.iter :i :before :after :tail :ret
<syntaxhighlight lang="logo">to equilibrium.iter :i :before :after :tail :ret
if equal? :before :after [make "ret lput :i :ret]
if equal? :before :after [make "ret lput :i :ret]
if empty? butfirst :tail [output :ret]
if empty? butfirst :tail [output :ret]
Line 1,673: Line 1,673:
end
end


show equilibrium_index [-7 1 5 2 -4 3 0] ; [4 7]</lang>
show equilibrium_index [-7 1 5 2 -4 3 0] ; [4 7]</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang="lua">
function array_sum(t)
function array_sum(t)
assert(type(t) == "table", "t must be a table!")
assert(type(t) == "table", "t must be a table!")
Line 1,700: Line 1,700:
print(equilibrium_index({-7, 1, 5, 2, -4, 3, 0}))
print(equilibrium_index({-7, 1, 5, 2, -4, 3, 0}))


</syntaxhighlight>
</lang>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{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.
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.
<lang Mathematica>equilibriumIndex[data_]:=Reap[
<syntaxhighlight lang="mathematica">equilibriumIndex[data_]:=Reap[
Do[If[Total[data[[;; n - 1]]] == Total[data[[n + 1 ;;]]],Sow[n]],
Do[If[Total[data[[;; n - 1]]] == Total[data[[n + 1 ;;]]],Sow[n]],
{n, Length[data]}]][[2, 1]]</lang>
{n, Length[data]}]][[2, 1]]</syntaxhighlight>
{{out|Usage}}
{{out|Usage}}
<pre>equilibriumIndex[{-7 , 1, 5 , 2, -4 , 3, 0}]
<pre>equilibriumIndex[{-7 , 1, 5 , 2, -4 , 3, 0}]
Line 1,712: Line 1,712:
=={{header|MATLAB}}==
=={{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.
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.
<lang MATLAB>function indicies = equilibriumIndex(list)
<syntaxhighlight lang="matlab">function indicies = equilibriumIndex(list)


indicies = [];
indicies = [];
Line 1,722: Line 1,722:
end
end


end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<lang MATLAB>>> equilibriumIndex([-7 1 5 2 -4 3 0])
<syntaxhighlight lang="matlab">>> equilibriumIndex([-7 1 5 2 -4 3 0])


ans =
ans =


4 7</lang>
4 7</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|Java}}
{{trans|Java}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,769: Line 1,769:
return
return


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,781: Line 1,781:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<lang nim>import math, sequtils, strutils
<syntaxhighlight lang="nim">import math, sequtils, strutils
iterator eqindex(data: openArray[int]): int =
iterator eqindex(data: openArray[int]): int =
Line 1,800: Line 1,800:
for data in d:
for data in d:
echo "d = [", data.join(", "), ']'
echo "d = [", data.join(", "), ']'
echo "eqIndex(d) -> [", toSeq(eqindex(data)).join(", "), ']'</lang>
echo "eqIndex(d) -> [", toSeq(eqindex(data)).join(", "), ']'</syntaxhighlight>


{{out}}
{{out}}
Line 1,814: Line 1,814:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{Trans|Java}}
{{Trans|Java}}
<lang objeck>class Rosetta {
<syntaxhighlight lang="objeck">class Rosetta {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
sequence := [-7, 1, 5, 2, -4, 3, 0];
sequence := [-7, 1, 5, 2, -4, 3, 0];
Line 1,837: Line 1,837:
};
};
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 1,846: Line 1,846:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let lst = [ -7; 1; 5; 2; -4; 3; 0 ]
<syntaxhighlight lang="ocaml">let lst = [ -7; 1; 5; 2; -4; 3; 0 ]
let sum = List.fold_left ( + ) 0 lst
let sum = List.fold_left ( + ) 0 lst


Line 1,860: Line 1,860:
print_string "Results:";
print_string "Results:";
List.iter (Printf.printf " %d") res;
List.iter (Printf.printf " %d") res;
print_newline ()</lang>
print_newline ()</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 1,866: Line 1,866:
Oforth collections are 1-based
Oforth collections are 1-based


<lang Oforth>: equilibrium(l)
<syntaxhighlight lang="oforth">: equilibrium(l)
| ls rs i e |
| ls rs i e |
0 ->ls
0 ->ls
Line 1,874: Line 1,874:
rs e - dup ->rs ls == ifTrue: [ i over add ]
rs e - dup ->rs ls == ifTrue: [ i over add ]
ls e + ->ls
ls e + ->ls
] ;</lang>
] ;</syntaxhighlight>


{{out}}
{{out}}
Line 1,884: Line 1,884:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
This uses 1-based vectors instead of 0-based arrays; subtract 1 from each index if you prefer the other style.
This uses 1-based vectors instead of 0-based arrays; subtract 1 from each index if you prefer the other style.
<lang parigp>equilib(v)={
<syntaxhighlight lang="parigp">equilib(v)={
my(a=sum(i=2,#v,v[i]),b=0,u=[]);
my(a=sum(i=2,#v,v[i]),b=0,u=[]);
for(i=1,#v-1,
for(i=1,#v-1,
Line 1,892: Line 1,892:
);
);
if(b,u,concat(u,#v))
if(b,u,concat(u,#v))
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>Program EquilibriumIndexDemo(output);
<syntaxhighlight lang="pascal">Program EquilibriumIndexDemo(output);


{$IFDEF FPC}{$Mode delphi}{$ENDIF}
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
Line 1,930: Line 1,930:
EquilibriumIndex(numbers, low(numbers));
EquilibriumIndex(numbers, low(numbers));
writeln;
writeln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>:> ./EquilibriumIndex
<pre>:> ./EquilibriumIndex
Line 1,939: Line 1,939:
slightly modified.Calculating the sum only once.Using a zero-based array type.Data type could be any type of signed integer or float.
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.
But beware, that during building the sum, the limits of the data type mustn't be violated.
<lang pascal>Program EquilibriumIndexDemo(output);
<syntaxhighlight lang="pascal">Program EquilibriumIndexDemo(output);
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
type
type
Line 2,024: Line 2,024:
numbers[i]:= 0;
numbers[i]:= 0;
TestRun(numbers);
TestRun(numbers);
end.</lang>{{out}}<pre>List of numbers: -7 1 5 2 -4 3 0
end.</syntaxhighlight>{{out}}<pre>List of numbers: -7 1 5 2 -4 3 0
Equilibirum indices: 3 6
Equilibirum indices: 3 6


Line 2,032: Line 2,032:
=={{header|Perl}}==
=={{header|Perl}}==
{{trans|Raku}}
{{trans|Raku}}
<lang perl>sub eq_index {
<syntaxhighlight lang="perl">sub eq_index {
my ( $i, $sum, %sums ) = ( 0, 0 );
my ( $i, $sum, %sums ) = ( 0, 0 );


Line 2,046: Line 2,046:
print eq_index qw( 2 4 6 ); # (no eq point)
print eq_index qw( 2 4 6 ); # (no eq point)
print eq_index qw( 2 9 2 ); # 1
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</lang>
print eq_index qw( 1 -1 1 -1 1 -1 1 ); # 0 1 2 3 4 5 6</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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: #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: Line 2,066:
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
(Remember that indices are 1-based in Phix)
(Remember that indices are 1-based in Phix)
Line 2,074: Line 2,074:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
$arr = array(-7, 1, 5, 2, -4, 3, 0);
$arr = array(-7, 1, 5, 2, -4, 3, 0);


Line 2,091: Line 2,091:
echo "# results:\n";
echo "# results:\n";
foreach (getEquilibriums($arr) as $r) echo "$r, ";
foreach (getEquilibriums($arr) as $r) echo "$r, ";
?></lang>
?></syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,103: Line 2,103:
===Prolog-style===
===Prolog-style===
{{trans|Prolog}}
{{trans|Prolog}}
<lang Picat>equilibrium_index1(A, Ix) =>
<syntaxhighlight lang="picat">equilibrium_index1(A, Ix) =>
append(Front, [_|Back], A),
append(Front, [_|Back], A),
sum(Front) = sum(Back),
sum(Front) = sum(Back),
Ix = length(Front)+1. % give 1 based index</lang>
Ix = length(Front)+1. % give 1 based index</syntaxhighlight>


===Loop approach===
===Loop approach===
{{trans|Java}}
{{trans|Java}}
<lang Picat>equilibrium_index2(A, Ix) =>
<syntaxhighlight lang="picat">equilibrium_index2(A, Ix) =>
Len = A.length,
Len = A.length,
Ix1 = [],
Ix1 = [],
Line 2,122: Line 2,122:
RunningSum := RunningSum + AI
RunningSum := RunningSum + AI
end,
end,
Ix = Ix1.</lang>
Ix = Ix1.</syntaxhighlight>


Test the approaches.
Test the approaches.
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
As = [
As = [
[-7, 1, 5, 2, -4, 3, 0], % 4 7
[-7, 1, 5, 2, -4, 3, 0], % 4 7
Line 2,156: Line 2,156:
println(r2=R2),
println(r2=R2),


nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 2,190: Line 2,190:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de equilibria (Lst)
<syntaxhighlight lang="picolisp">(de equilibria (Lst)
(make
(make
(let Sum 0
(let Sum 0
(for ((I . L) Lst L (cdr L))
(for ((I . L) Lst L (cdr L))
(and (= Sum (sum prog (cdr L))) (link I))
(and (= Sum (sum prog (cdr L))) (link I))
(inc 'Sum (car L)) ) ) ) )</lang>
(inc 'Sum (car L)) ) ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>: (equilibria (-7 1 5 2 -4 3 0))
<pre>: (equilibria (-7 1 5 2 -4 3 0))
Line 2,206: Line 2,206:
{{works with|PowerShell|2}}
{{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.
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 )
function Get-EquilibriumIndex ( $Sequence )
{
{
Line 2,229: Line 2,229:
return $EqulibriumIndex
return $EqulibriumIndex
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-EquilibriumIndex -7, 1, 5, 2, -4, 3, 0
Get-EquilibriumIndex -7, 1, 5, 2, -4, 3, 0
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,241: Line 2,241:
=={{header|Prolog}}==
=={{header|Prolog}}==


<lang prolog>equilibrium_index(List, Index) :-
<syntaxhighlight lang="prolog">equilibrium_index(List, Index) :-
append(Front, [_|Back], List),
append(Front, [_|Back], List),
sumlist(Front, Sum),
sumlist(Front, Sum),
sumlist(Back, Sum),
sumlist(Back, Sum),
length(Front, Len),
length(Front, Len),
Index is Len.</lang>
Index is Len.</syntaxhighlight>


Example:
Example:


<lang prolog>?- equilibrium_index([-7, 1, 5, 2, -4, 3, 0], Index).
<syntaxhighlight lang="prolog">?- equilibrium_index([-7, 1, 5, 2, -4, 3, 0], Index).
Index = 3 ;
Index = 3 ;
Index = 6 ;
Index = 6 ;
false.</lang>
false.</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
{{trans|Java}}
{{trans|Java}}
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
Define i, c=CountProgramParameters()-1
Define i, c=CountProgramParameters()-1
For i=0 To c
For i=0 To c
Line 2,270: Line 2,270:
If LSum=RSum: PrintN(Str(i)): EndIf
If LSum=RSum: PrintN(Str(i)): EndIf
Next i
Next i
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre>> Equilibrium.exe -7 1 5 2 -4 3 0
<pre>> Equilibrium.exe -7 1 5 2 -4 3 0
Line 2,279: Line 2,279:
===Two Pass===
===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.
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.
<lang python>def eqindex2Pass(data):
<syntaxhighlight lang="python">def eqindex2Pass(data):
"Two pass"
"Two pass"
suml, sumr, ddelayed = 0, sum(data), 0
suml, sumr, ddelayed = 0, sum(data), 0
Line 2,287: Line 2,287:
ddelayed = d
ddelayed = d
if suml == sumr:
if suml == sumr:
yield i</lang>
yield i</syntaxhighlight>
===Multi Pass===
===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:
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:
<lang python>def eqindexMultiPass(data):
<syntaxhighlight lang="python">def eqindexMultiPass(data):
"Multi pass"
"Multi pass"
for i in range(len(data)):
for i in range(len(data)):
suml, sumr = sum(data[:i]), sum(data[i+1:])
suml, sumr = sum(data[:i]), sum(data[i+1:])
if suml == sumr:
if suml == sumr:
yield i</lang>
yield i</syntaxhighlight>
Shorter alternative:
Shorter alternative:
<lang python>def eqindexMultiPass(s):
<syntaxhighlight lang="python">def eqindexMultiPass(s):
return [i for i in xrange(len(s)) if sum(s[:i]) == sum(s[i+1:])]
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])</lang>
print eqindexMultiPass([-7, 1, 5, 2, -4, 3, 0])</syntaxhighlight>
===One Pass===
===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.
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.
<lang python>from collections import defaultdict
<syntaxhighlight lang="python">from collections import defaultdict


def eqindex1Pass(data):
def eqindex1Pass(data):
Line 2,311: Line 2,311:
l += c
l += c
h[l * 2 - c].append(i)
h[l * 2 - c].append(i)
return h[l]</lang>
return h[l]</syntaxhighlight>
===Tests===
===Tests===
<lang python>f = (eqindex2Pass, eqindexMultiPass, eqindex1Pass)
<syntaxhighlight lang="python">f = (eqindex2Pass, eqindexMultiPass, eqindex1Pass)
d = ([-7, 1, 5, 2, -4, 3, 0],
d = ([-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
[2, 4, 6],
Line 2,322: Line 2,322:
print("d = %r" % data)
print("d = %r" % data)
for func in f:
for func in f:
print(" %16s(d) -> %r" % (func.__name__, list(func(data))))</lang>
print(" %16s(d) -> %r" % (func.__name__, list(func(data))))</syntaxhighlight>
{{out|Sample output}}
{{out|Sample output}}
<pre>d = [-7, 1, 5, 2, -4, 3, 0]
<pre>d = [-7, 1, 5, 2, -4, 3, 0]
Line 2,346: Line 2,346:


The ''right'' scan can be derived from the left as a map or equivalent list comprehension:
The ''right'' scan can be derived from the left as a map or equivalent list comprehension:
<lang python>"""Equilibrium index"""
<syntaxhighlight lang="python">"""Equilibrium index"""


from itertools import (accumulate)
from itertools import (accumulate)
Line 2,410: Line 2,410:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Equilibrium indices:
<pre>Equilibrium indices:
Line 2,422: Line 2,422:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(define (subsums xs)
(define (subsums xs)
Line 2,438: Line 2,438:


(equivilibrium '(-7 1 5 2 -4 3 0))
(equivilibrium '(-7 1 5 2 -4 3 0))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang racket>
<syntaxhighlight lang="racket">
'(3 6)
'(3 6)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>sub equilibrium_index(@list) {
<syntaxhighlight lang="raku" line>sub equilibrium_index(@list) {
my ($left,$right) = 0, [+] @list;
my ($left,$right) = 0, [+] @list;


Line 2,457: Line 2,457:


my @list = -7, 1, 5, 2, -4, 3, 0;
my @list = -7, 1, 5, 2, -4, 3, 0;
.say for equilibrium_index(@list).grep(/\d/);</lang>
.say for equilibrium_index(@list).grep(/\d/);</syntaxhighlight>
And here's an FP solution that manages to remain O(n):
And here's an FP solution that manages to remain O(n):
<lang perl6>sub equilibrium_index(@list) {
<syntaxhighlight lang="raku" line>sub equilibrium_index(@list) {
my @a = [\+] @list;
my @a = [\+] @list;
my @b = reverse [\+] reverse @list;
my @b = reverse [\+] reverse @list;
^@list Zxx (@a »==« @b);
^@list Zxx (@a »==« @b);
}</lang>
}</syntaxhighlight>
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.
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 ===
=== Single-pass solution ===
Line 2,476: Line 2,476:
Therefore (by substituting L for R), L + C + L == S at all equilibrium points.<br>
Therefore (by substituting L for R), L + C + L == S at all equilibrium points.<br>
Restated, 2L + C == S.
Restated, 2L + C == S.
<lang perl6># Original example, with expanded calculations:
<syntaxhighlight lang="raku" line># Original example, with expanded calculations:
0 1 2 3 4 5 6 # Index
0 1 2 3 4 5 6 # Index
-7 1 5 2 -4 3 0 # C (Value at index)
-7 1 5 2 -4 3 0 # C (Value at index)
0 -7 -6 -1 1 -3 0 # L (Sum of left)
0 -7 -6 -1 1 -3 0 # L (Sum of left)
-7 -13 -7 0 -2 -3 0 # 2L+C</lang>
-7 -13 -7 0 -2 -3 0 # 2L+C</syntaxhighlight>
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:
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:
<lang perl6>{
<syntaxhighlight lang="raku" line>{
-7 => [ 0, 2 ],
-7 => [ 0, 2 ],
-13 => [ 1 ],
-13 => [ 1 ],
Line 2,488: Line 2,488:
-2 => [ 4 ],
-2 => [ 4 ],
-3 => [ 5 ],
-3 => [ 5 ],
}</lang>
}</syntaxhighlight>
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.
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.
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.
<lang perl6>sub eq_index ( *@list ) {
<syntaxhighlight lang="raku" line>sub eq_index ( *@list ) {
my $sum = 0;
my $sum = 0;


Line 2,506: Line 2,506:
say eq_index < 2 4 6 >; # (no eq point)
say eq_index < 2 4 6 >; # (no eq point)
say eq_index < 2 9 2 >; # 1
say eq_index < 2 9 2 >; # 1
say eq_index < 1 -1 1 -1 1 -1 1 >; # 0 1 2 3 4 5 6</lang>
say eq_index < 1 -1 1 -1 1 -1 1 >; # 0 1 2 3 4 5 6</syntaxhighlight>
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.
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.
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}}==
=={{header|Red}}==
<lang Rebol>Red []
<syntaxhighlight lang="rebol">Red []
eqindex: func [a [block!]] [
eqindex: func [a [block!]] [
collect [
collect [
Line 2,519: Line 2,519:
prin "(1 based) equ indices are: "
prin "(1 based) equ indices are: "
probe eqindex [-7 1 5 2 -4 3 0]
probe eqindex [-7 1 5 2 -4 3 0]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>(1 based) equ indices are: [4 7]</pre>
<pre>(1 based) equ indices are: [4 7]</pre>


=={{header|ReScript}}==
=={{header|ReScript}}==
<lang ReScript>let arr = [-7, 1, 5, 2, -4, 3, 0]
<syntaxhighlight lang="rescript">let arr = [-7, 1, 5, 2, -4, 3, 0]
let sum = Js.Array2.reduce(arr, \"+", 0)
let sum = Js.Array2.reduce(arr, \"+", 0)
let len = Js.Array.length(arr)
let len = Js.Array.length(arr)
Line 2,540: Line 2,540:
let res = aux([], 0, 0, sum)
let res = aux([], 0, 0, sum)
Js.log("Results:")
Js.log("Results:")
Js.Array2.forEach(res, Js.log)</lang>
Js.Array2.forEach(res, Js.log)</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 2,546: Line 2,546:
This REXX version utilizes a &nbsp; ''zero-based'' &nbsp; stemmed array to mimic the illustrative example in this Rosetta Code task's
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.
<br>prologue, &nbsp; which uses a &nbsp; ''zero-based'' &nbsp; index.
<lang rexx>/*REXX program calculates and displays the equilibrium index for a numeric array (list).*/
<syntaxhighlight lang="rexx">/*REXX program calculates and displays the equilibrium index for a numeric array (list).*/
parse arg x /*obtain the optional arguments from CL*/
parse arg x /*obtain the optional arguments from CL*/
if x='' then x= copies(" 7 -7", 50) 7 /*Not specified? Then use the default.*/
if x='' then x= copies(" 7 -7", 50) 7 /*Not specified? Then use the default.*/
Line 2,562: Line 2,562:
if sum==0 then $= $ i
if sum==0 then $= $ i
end /*i*/ /* [↑] Zero? Found an equilibrium index*/
end /*i*/ /* [↑] Zero? Found an equilibrium index*/
return $ /*return equilibrium list (may be null)*/</lang>
return $ /*return equilibrium list (may be null)*/</syntaxhighlight>
{{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>}}
{{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>
<pre>
Line 2,589: Line 2,589:


===version 2===
===version 2===
<lang rexx>/* REXX ---------------------------------------------------------------
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 30.06.2014 Walter Pachl
* 30.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
*--------------------------------------------------------------------*/
Line 2,621: Line 2,621:
eil=eil im1
eil=eil im1
End
End
Return eil</lang>
Return eil</syntaxhighlight>
'''output'''
'''output'''
<pre> array list: -7 1 5 2 -4 3 0
<pre> array list: -7 1 5 2 -4 3 0
Line 2,637: Line 2,637:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
list = [-7, 1, 5, 2, -4, 3, 0]
list = [-7, 1, 5, 2, -4, 3, 0]
see "equilibrium indices are : " + equilibrium(list) + nl
see "equilibrium indices are : " + equilibrium(list) + nl
Line 2,652: Line 2,652:
e = left(e,len(e)-1)
e = left(e,len(e)-1)
return e
return e
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,661: Line 2,661:


;Functional Style
;Functional Style
<lang ruby>def eq_indices(list)
<syntaxhighlight lang="ruby">def eq_indices(list)
list.each_index.select do |i|
list.each_index.select do |i|
list[0...i].sum == list[i+1..-1].sum
list[0...i].sum == list[i+1..-1].sum
end
end
end</lang>
end</syntaxhighlight>
;Tail Recursion
;Tail Recursion
* This one would be good if Ruby did tail-call optimization (TCO).
* 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).
* [[MRI]] does not do TCO; so this function fails with a long list (by overflowing the call stack).
<lang ruby>def eq_indices(list)
<syntaxhighlight lang="ruby">def eq_indices(list)
result = []
result = []
list.empty? and return result
list.empty? and return result
Line 2,682: Line 2,682:
helper.call 0, list.first, list.drop(1).sum, 0
helper.call 0, list.first, list.drop(1).sum, 0
result
result
end</lang>
end</syntaxhighlight>
;Imperative Style (faster)
;Imperative Style (faster)
<lang ruby>def eq_indices(list)
<syntaxhighlight lang="ruby">def eq_indices(list)
left, right = 0, list.sum
left, right = 0, list.sum
equilibrium_indices = []
equilibrium_indices = []
Line 2,695: Line 2,695:
equilibrium_indices
equilibrium_indices
end</lang>
end</syntaxhighlight>


;Test
;Test
<lang ruby>indices = [
<syntaxhighlight lang="ruby">indices = [
[-7, 1, 5, 2,-4, 3, 0],
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
[2, 4, 6],
Line 2,706: Line 2,706:
indices.each do |x|
indices.each do |x|
puts "%p => %p" % [x, eq_indices(x)]
puts "%p => %p" % [x, eq_indices(x)]
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,716: Line 2,716:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
extern crate num;
extern crate num;


Line 2,741: Line 2,741:
println!("Equilibrium indices for {:?} are: {:?}", v, indices);
println!("Equilibrium indices for {:?} are: {:?}", v, indices);
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,749: Line 2,749:
=={{header|Scala}}==
=={{header|Scala}}==


<lang Scala> def getEquilibriumIndex(A: Array[Int]): Int = {
<syntaxhighlight lang="scala"> def getEquilibriumIndex(A: Array[Int]): Int = {
val bigA: Array[BigInt] = A.map(BigInt(_))
val bigA: Array[BigInt] = A.map(BigInt(_))
val partialSums: Array[BigInt] = bigA.scanLeft(BigInt(0))(_+_).tail
val partialSums: Array[BigInt] = bigA.scanLeft(BigInt(0))(_+_).tail
Line 2,756: Line 2,756:
def isRandLSumEqual(i: Int): Boolean = lSum(i) == rSum(i)
def isRandLSumEqual(i: Int): Boolean = lSum(i) == rSum(i)
(0 until partialSums.length).find(isRandLSumEqual).getOrElse(-1)
(0 until partialSums.length).find(isRandLSumEqual).getOrElse(-1)
} </lang>
} </syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const array integer: numList is [] (-7, 1, 5, 2, -4, 3, 0);
const array integer: numList is [] (-7, 1, 5, 2, -4, 3, 0);
Line 2,798: Line 2,798:
end for;
end for;
writeln;
writeln;
end func;</lang>
end func;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,805: Line 2,805:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func eq_index(nums) {
<syntaxhighlight lang="ruby">func eq_index(nums) {
var (i, sum, sums) = (0, 0, Hash.new);
var (i, sum, sums) = (0, 0, Hash.new);
nums.each { |n|
nums.each { |n|
Line 2,812: Line 2,812:
}
}
sums{sum} \\ [];
sums{sum} \\ [];
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang ruby>var indices = [
<syntaxhighlight lang="ruby">var indices = [
[-7, 1, 5, 2,-4, 3, 0],
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
[2, 4, 6],
Line 2,824: Line 2,824:
for x in indices {
for x in indices {
say ("%s => %s" % @|[x, eq_index(x)].map{.dump});
say ("%s => %s" % @|[x, eq_index(x)].map{.dump});
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,835: Line 2,835:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>extension Collection where Element: Numeric {
<syntaxhighlight lang="swift">extension Collection where Element: Numeric {
func equilibriumIndexes() -> [Index] {
func equilibriumIndexes() -> [Index] {
guard !isEmpty else {
guard !isEmpty else {
Line 2,862: Line 2,862:
let arr = [-7, 1, 5, 2, -4, 3, 0]
let arr = [-7, 1, 5, 2, -4, 3, 0]


print("Equilibrium indexes of \(arr): \(arr.equilibriumIndexes())")</lang>
print("Equilibrium indexes of \(arr): \(arr.equilibriumIndexes())")</syntaxhighlight>


{{out}}
{{out}}
Line 2,869: Line 2,869:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc listEquilibria {list} {
<syntaxhighlight lang="tcl">proc listEquilibria {list} {
set after 0
set after 0
foreach item $list {incr after $item}
foreach item $list {incr after $item}
Line 2,884: Line 2,884:
}
}
return $result
return $result
}</lang>
}</syntaxhighlight>
;Example of use
;Example of use
<lang tcl>set testData {-7 1 5 2 -4 3 0}
<syntaxhighlight lang="tcl">set testData {-7 1 5 2 -4 3 0}
puts Equilibria=[join [listEquilibria $testData] ", "]</lang>
puts Equilibria=[join [listEquilibria $testData] ", "]</syntaxhighlight>
{{out}}
{{out}}
<pre>Equilibria=3, 6</pre>
<pre>Equilibria=3, 6</pre>


=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import int
#import int


Line 2,899: Line 2,899:
#cast %nL
#cast %nL


example = edex <-7,1,5,2,-4,3,0></lang>
example = edex <-7,1,5,2,-4,3,0></syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,907: Line 2,907:
=={{header|VBScript}}==
=={{header|VBScript}}==
Solution adopted from http://www.geeksforgeeks.org/equilibrium-index-of-an-array/ .
Solution adopted from http://www.geeksforgeeks.org/equilibrium-index-of-an-array/ .
<lang vb>arr = Array(-7,1,5,2,-4,3,0)
<syntaxhighlight lang="vb">arr = Array(-7,1,5,2,-4,3,0)
WScript.StdOut.Write equilibrium(arr,UBound(arr))
WScript.StdOut.Write equilibrium(arr,UBound(arr))
WScript.StdOut.WriteLine
WScript.StdOut.WriteLine
Line 2,925: Line 2,925:
leftsum = leftsum + arr(i)
leftsum = leftsum + arr(i)
Next
Next
End Function</lang>
End Function</syntaxhighlight>


{{out}}
{{out}}
Line 2,932: Line 2,932:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt


var equilibrium = Fn.new { |a|
var equilibrium = Fn.new { |a|
Line 2,960: Line 2,960:
for (test in tests) {
for (test in tests) {
System.print("%(Fmt.s(24, test)) -> %(equilibrium.call(test))")
System.print("%(Fmt.s(24, test)) -> %(equilibrium.call(test))")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,975: Line 2,975:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>code Ran=1, ChOut=8, IntOut=11;
<syntaxhighlight lang="xpl0">code Ran=1, ChOut=8, IntOut=11;
def Size = 1_000_000;
def Size = 1_000_000;
int I, S, A(Size), Hi(Size), Lo(Size);
int I, S, A(Size), Hi(Size), Lo(Size);
Line 2,985: Line 2,985:
for I:= 0 to Size-1 do
for I:= 0 to Size-1 do
if Lo(I) = Hi(I) then [IntOut(0, I); ChOut(0, ^ )];
if Lo(I) = Hi(I) then [IntOut(0, I); ChOut(0, ^ )];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,994: Line 2,994:
=={{header|Yorick}}==
=={{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.
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.
<lang yorick>func equilibrium_indices(A) {
<syntaxhighlight lang="yorick">func equilibrium_indices(A) {
return where(A(psum) == A(::-1)(psum)(::-1));
return where(A(psum) == A(::-1)(psum)(::-1));
}</lang>
}</syntaxhighlight>
{{out|Example interactive usage}}
{{out|Example interactive usage}}
<pre>> equilibrium_indices([-7, 1, 5, 2, -4, 3, 0])
<pre>> equilibrium_indices([-7, 1, 5, 2, -4, 3, 0])
Line 3,003: Line 3,003:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|Clojure}}
{{trans|Clojure}}
<lang zkl>fcn equilibrium(lst){ // two pass
<syntaxhighlight lang="zkl">fcn equilibrium(lst){ // two pass
reg acc=List(), left=0,right=lst.sum(0),i=0;
reg acc=List(), left=0,right=lst.sum(0),i=0;
foreach x in (lst){
foreach x in (lst){
Line 3,011: Line 3,011:
}
}
acc
acc
}</lang>
}</syntaxhighlight>
{{trans|D}}
{{trans|D}}
<lang zkl>fcn equilibrium(lst){ // lst should immutable, n^2
<syntaxhighlight 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) })
(0).filter(lst.len(),'wrap(n){ lst[0,n].sum(0) == lst[n+1,*].sum(0) })
}</lang>
}</syntaxhighlight>
If the input list is immutable, no new lists are generated (other than accumulating the result).
If the input list is immutable, no new lists are generated (other than accumulating the result).
<lang zkl>equilibrium(T(-7, 1, 5, 2, -4, 3, 0)).println();</lang>
<syntaxhighlight lang="zkl">equilibrium(T(-7, 1, 5, 2, -4, 3, 0)).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>L(3,6)</pre>
<pre>L(3,6)</pre>
Line 3,023: Line 3,023:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
{{trans|AWK}}
<lang zxbasic>10 DATA 7,-7,1,5,2,-4,3,0
<syntaxhighlight lang="zxbasic">10 DATA 7,-7,1,5,2,-4,3,0
20 READ n
20 READ n
30 DIM a(n): LET sum=0: LET leftsum=0: LET s$=""
30 DIM a(n): LET sum=0: LET leftsum=0: LET s$=""
Line 3,034: Line 3,034:
100 PRINT "Numbers: ";
100 PRINT "Numbers: ";
110 FOR i=1 TO n: PRINT a(i);" ";: NEXT i
110 FOR i=1 TO n: PRINT a(i);" ";: NEXT i
120 PRINT '"Indices: ";s$</lang>
120 PRINT '"Indices: ";s$</syntaxhighlight>