Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Equilibrium_index

View file

@ -0,0 +1,32 @@
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence &nbsp; <big><math>A</math></big>:
::::: &nbsp; <big><math>A_0 = -7</math></big>
::::: &nbsp; <big><math>A_1 = 1</math></big>
::::: &nbsp; <big><math>A_2 = 5</math></big>
::::: &nbsp; <big><math>A_3 = 2</math></big>
::::: &nbsp; <big><math>A_4 = -4</math></big>
::::: &nbsp; <big><math>A_5 = 3</math></big>
::::: &nbsp; <big><math>A_6 = 0</math></big>
3 &nbsp; is an equilibrium index, because:
::::: &nbsp; <big><math>A_0 + A_1 + A_2 = A_4 + A_5 + A_6</math></big>
6 &nbsp; is also an equilibrium index, because:
::::: &nbsp; <big><math>A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0</math></big>
(sum of zero elements is zero)
7 &nbsp; is not an equilibrium index, because it is not a valid index of sequence <big><math>A</math></big>.
;Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
<br><br>

View file

@ -0,0 +1,4 @@
F eqindex(arr)
R (0 .< arr.len).filter(i -> sum(@arr[0.<i]) == sum(@arr[i+1..]))
print(eqindex([-7, 1, 5, 2, -4, 3, 0]))

View file

@ -0,0 +1,14 @@
REPORT equilibrium_index.
TYPES: y_i TYPE STANDARD TABLE OF i WITH EMPTY KEY.
cl_demo_output=>display( REDUCE y_i( LET sequences = VALUE y_i( ( -7 ) ( 1 ) ( 5 ) ( 2 ) ( -4 ) ( 3 ) ( 0 ) )
total_sum = REDUCE #( INIT sum = 0
FOR sequence IN sequences
NEXT sum = sum + ( sequence ) ) IN
INIT x = VALUE y_i( )
y = 0
FOR i = 1 UNTIL i > lines( sequences )
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 ) ).

View file

@ -0,0 +1,25 @@
MODE YIELDINT = PROC(INT)VOID;
PROC gen equilibrium index = ([]INT arr, YIELDINT yield)VOID:
(
INT sum := 0;
FOR i FROM LWB arr TO UPB arr DO
sum +:= arr[i]
OD;
INT left:=0, right:=sum;
FOR i FROM LWB arr TO UPB arr DO
right -:= arr[i];
IF left = right THEN yield(i) FI;
left +:= arr[i]
OD
);
test:(
[]INT arr = []INT(-7, 1, 5, 2, -4, 3, 0)[@0];
# FOR INT index IN # gen equilibrium index(arr, # ) DO ( #
## (INT index)VOID:
print(index)
# OD # );
print(new line)
)

View file

@ -0,0 +1,27 @@
# syntax: GAWK -f EQUILIBRIUM_INDEX.AWK
BEGIN {
main("-7 1 5 2 -4 3 0")
main("2 4 6")
main("2 9 2")
main("1 -1 1 -1 1 -1 1")
exit(0)
}
function main(numbers, x) {
x = equilibrium(numbers)
printf("numbers: %s\n",numbers)
printf("indices: %s\n\n",length(x)==0?"none":x)
}
function equilibrium(numbers, arr,i,leftsum,leng,str,sum) {
leng = split(numbers,arr," ")
for (i=1; i<=leng; i++) {
sum += arr[i]
}
for (i=1; i<=leng; i++) {
sum -= arr[i]
if (leftsum == sum) {
str = str i " "
}
leftsum += arr[i]
}
return(str)
}

View file

@ -0,0 +1,60 @@
PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
INT FUNC SumRange(INT ARRAY a INT first,last)
INT sum
INT i
sum=0
FOR i=first TO last
DO
sum==+a(i)
OD
RETURN(sum)
PROC EquilibriumIndices(INT ARRAY a INT size
INT ARRAY indices INT POINTER indSize)
INT i,left,right
indSize^=0
FOR i=0 TO size-1
DO
left=SumRange(a,0,i-1)
right=SumRange(a,i+1,size-1)
IF left=right THEN
indices(indSize^)=i
indSize^==+1
FI
OD
RETURN
PROC Test(INT ARRAY a INT size)
INT ARRAY indices(100)
INT indSize
EquilibriumIndices(a,size,indices,@indSize)
Print("Array=") PrintArray(a,size)
Print("Equilibrium indices=") PrintArray(indices,indSize)
PutE()
RETURN
PROC Main()
INT ARRAY a=[65529 1 5 2 65532 3 0]
INT ARRAY b=[65535 1 65535 1 65535 1 65535]
INT ARRAY c=[1 2 3 4 5 6 7 8 9]
INT ARRAY d=[0]
Test(a,7)
Test(b,7)
Test(c,9)
Test(d,1)
RETURN

View file

@ -0,0 +1,18 @@
with Ada.Containers.Vectors;
generic
type Index_Type is range <>;
type Element_Type is private;
Zero : Element_Type;
with function "+" (Left, Right : Element_Type) return Element_Type is <>;
with function "-" (Left, Right : Element_Type) return Element_Type is <>;
with function "=" (Left, Right : Element_Type) return Boolean is <>;
type Array_Type is private;
with function Element (From : Array_Type; Key : Index_Type) return Element_Type is <>;
package Equilibrium is
package Index_Vectors is new Ada.Containers.Vectors
(Index_Type => Positive, Element_Type => Index_Type);
function Get_Indices (From : Array_Type) return Index_Vectors.Vector;
end Equilibrium;

View file

@ -0,0 +1,20 @@
package body Equilibrium is
function Get_Indices (From : Array_Type) return Index_Vectors.Vector is
Result : Index_Vectors.Vector;
Right_Sum, Left_Sum : Element_Type := Zero;
begin
for Index in Index_Type'Range loop
Right_Sum := Right_Sum + Element (From, Index);
end loop;
for Index in Index_Type'Range loop
Right_Sum := Right_Sum - Element (From, Index);
if Left_Sum = Right_Sum then
Index_Vectors.Append (Result, Index);
end if;
Left_Sum := Left_Sum + Element (From, Index);
end loop;
return Result;
end Get_Indices;
end Equilibrium;

View file

@ -0,0 +1,52 @@
with Ada.Text_IO;
with Equilibrium;
with Ada.Containers.Vectors;
procedure Main is
subtype Index_Type is Positive range 1 .. 7;
package Vectors is new Ada.Containers.Vectors
(Element_Type => Integer, Index_Type => Index_Type);
type Plain_Array is array (Index_Type) of Integer;
function Element (From : Plain_Array; Key : Index_Type) return Integer is
begin
return From (Key);
end Element;
package Vector_Equilibrium is new Equilibrium
(Index_Type => Index_Type,
Element_Type => Integer,
Zero => 0,
Array_Type => Vectors.Vector,
Element => Vectors.Element);
package Array_Equilibrium is new Equilibrium
(Index_Type => Index_Type,
Element_Type => Integer,
Zero => 0,
Array_Type => Plain_Array);
My_Vector : Vectors.Vector;
My_Array : Plain_Array := (-7, 1, 5, 2, -4, 3, 0);
Vector_Result : Vector_Equilibrium.Index_Vectors.Vector;
Array_Result : Array_Equilibrium.Index_Vectors.Vector :=
Array_Equilibrium.Get_Indices (My_Array);
begin
Vectors.Append (My_Vector, -7);
Vectors.Append (My_Vector, 1);
Vectors.Append (My_Vector, 5);
Vectors.Append (My_Vector, 2);
Vectors.Append (My_Vector, -4);
Vectors.Append (My_Vector, 3);
Vectors.Append (My_Vector, 0);
Vector_Result := Vector_Equilibrium.Get_Indices (My_Vector);
Ada.Text_IO.Put_Line ("Results:");
Ada.Text_IO.Put ("Array: ");
for I in Array_Result.First_Index .. Array_Result.Last_Index loop
Ada.Text_IO.Put (Integer'Image (Array_Equilibrium.Index_Vectors.Element (Array_Result, I)));
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("Vector: ");
for I in Vector_Result.First_Index .. Vector_Result.Last_Index loop
Ada.Text_IO.Put (Integer'Image (Vector_Equilibrium.Index_Vectors.Element (Vector_Result, I)));
end loop;
Ada.Text_IO.New_Line;
end Main;

View file

@ -0,0 +1,68 @@
with Ada.Text_IO;
procedure Equilibrium is
type Integer_Sequence is array (Positive range <>) of Integer;
function Seq_Img (From : Integer_Sequence) return String is
begin
if From'First /= From'Last then
return " " & Integer'Image (From (From'First)) &
Seq_Img (From (From'First + 1 .. From'Last));
else
return " " & Integer'Image (From (From'First));
end if;
end Seq_Img;
type Boolean_Sequence is array (Positive range <>) of Boolean;
function Seq_Img (From : Boolean_Sequence) return String is
begin
if From'First > From'Last then
return "";
end if;
if From (From'First) then
return Integer'Image (From'First) &
Seq_Img (From (From'First + 1 .. From'Last));
else
return Seq_Img (From (From'First + 1 .. From'Last));
end if;
end Seq_Img;
function Get_Indices (From : Integer_Sequence) return Boolean_Sequence is
Result : Boolean_Sequence (From'Range) := (others => False);
Left_Sum, Right_Sum : Integer := 0;
begin
for Index in From'Range loop
Right_Sum := Right_Sum + From (Index);
end loop;
for Index in From'Range loop
Right_Sum := Right_Sum - From (Index);
Result (Index) := Left_Sum = Right_Sum;
Left_Sum := Left_Sum + From (Index);
end loop;
return Result;
end Get_Indices;
X1 : Integer_Sequence := (-7, 1, 5, 2, -4, 3, 0);
X1_Result : Boolean_Sequence := Get_Indices (X1);
X2 : Integer_Sequence := ( 2, 4, 6);
X2_Result : Boolean_Sequence := Get_Indices (X2);
X3 : Integer_Sequence := ( 2, 9, 2);
X3_Result : Boolean_Sequence := Get_Indices (X3);
X4 : Integer_Sequence := ( 1, -1, 1, -1, 1 ,-1, 1);
X4_Result : Boolean_Sequence := Get_Indices (X4);
begin
Ada.Text_IO.Put_Line ("Results:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("X1:" & Seq_Img (X1));
Ada.Text_IO.Put_Line ("Eqs:" & Seq_Img (X1_Result));
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("X2:" & Seq_Img (X2));
Ada.Text_IO.Put_Line ("Eqs:" & Seq_Img (X2_Result));
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("X3:" & Seq_Img (X3));
Ada.Text_IO.Put_Line ("Eqs:" & Seq_Img (X3_Result));
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("X4:" & Seq_Img (X4));
Ada.Text_IO.Put_Line ("Eqs:" & Seq_Img (X4_Result));
end Equilibrium;

View file

@ -0,0 +1,25 @@
list
eqindex(list l)
{
integer e, i, s, sum;
list x;
s = sum = 0;
l.ucall(add_i, 1, sum);
for (i, e in l) {
if (s * 2 + e == sum) {
x.append(i);
}
s += e;
}
x;
}
integer
main(void)
{
list(-7, 1, 5, 2, -4, 3, 0).eqindex.ucall(o_, 0, "\n");
0;
}

View file

@ -0,0 +1,178 @@
-- equilibriumIndices :: [Int] -> [Int]
on equilibriumIndices(xs)
script balancedPair
on |λ|(a, pair, i)
set {x, y} to pair
if x = y then
{i - 1} & a
else
a
end if
end |λ|
end script
script plus
on |λ|(a, b)
a + b
end |λ|
end script
-- Fold over zipped pairs of sums from left
-- and sums from right
foldr(balancedPair, {}, ¬
zip(scanl1(plus, xs), scanr1(plus, xs)))
end equilibriumIndices
-- TEST -----------------------------------------------------------------------
on run
map(equilibriumIndices, {¬
{-7, 1, 5, 2, -4, 3, 0}, ¬
{2, 4, 6}, ¬
{2, 9, 2}, ¬
{1, -1, 1, -1, 1, -1, 1}, ¬
{1}, ¬
{}})
--> {{3, 6}, {}, {1}, {0, 1, 2, 3, 4, 5, 6}, {0}, {}}
end run
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
-- init :: [a] -> [a]
on init(xs)
set lng to length of xs
if lng > 1 then
items 1 thru -2 of xs
else if lng > 0 then
{}
else
missing value
end if
end init
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- scanl :: (b -> a -> b) -> b -> [a] -> [b]
on scanl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
set lst to {startValue}
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
set end of lst to v
end repeat
return lst
end tell
end scanl
-- scanl1 :: (a -> a -> a) -> [a] -> [a]
on scanl1(f, xs)
if length of xs > 0 then
scanl(f, item 1 of xs, tail(xs))
else
{}
end if
end scanl1
-- scanr :: (b -> a -> b) -> b -> [a] -> [b]
on scanr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
set lst to {startValue}
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
set end of lst to v
end repeat
return reverse of lst
end tell
end scanr
-- scanr1 :: (a -> a -> a) -> [a] -> [a]
on scanr1(f, xs)
if length of xs > 0 then
scanr(f, item -1 of xs, init(xs))
else
{}
end if
end scanr1
-- tail :: [a] -> [a]
on tail(xs)
if length of xs > 1 then
items 2 thru -1 of xs
else
{}
end if
end tail
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
repeat with i from 1 to lng
set end of lst to {item i of xs, item i of ys}
end repeat
return lst
end zip

View file

@ -0,0 +1,22 @@
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})

View file

@ -0,0 +1 @@
{4, 7}

View file

@ -0,0 +1,23 @@
eqIndex: function [row][
suml: 0
delayed: 0
sumr: sum row
result: new []
loop.with:'i row 'r [
suml: suml + delayed
sumr: sumr - r
delayed: r
if suml = sumr -> 'result ++ i
]
return result
]
data: @[
@[neg 7, 1, 5, 2, neg 4, 3, 0]
@[2 4 6]
@[2 9 2]
@[1 neg 1 1 neg 1 1 neg 1 1]
]
loop data 'd ->
print [pad.right join.with:", " to [:string] d 25 "=> equilibrium index:" eqIndex d]

View file

@ -0,0 +1,14 @@
Equilibrium_index(list, BaseIndex=0){
StringSplit, A, list, `,
Loop % A0 {
i := A_Index , Pre := Post := 0
loop, % A0
if (A_Index < i)
Pre += A%A_Index%
else if (A_Index > i)
Post += A%A_Index%
if (Pre = Post)
Res .= (Res?", ":"") i - (BaseIndex?0:1)
}
return Res
}

View file

@ -0,0 +1,2 @@
list = -7, 1, 5, 2, -4, 3, 0
MsgBox % Equilibrium_index(list)

View file

@ -0,0 +1,19 @@
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

View file

@ -0,0 +1,13 @@
DIM list(6)
list() = -7, 1, 5, 2, -4, 3, 0
PRINT "Equilibrium indices are " FNequilibrium(list())
END
DEF FNequilibrium(l())
LOCAL i%, r, s, e$
s = SUM(l())
FOR i% = 0 TO DIM(l(),1)
IF r = s - r - l(i%) THEN e$ += STR$(i%) + ","
r += l(i%)
NEXT
= LEFT$(e$)

View file

@ -0,0 +1,42 @@
@echo off
setlocal enabledelayedexpansion
call :equilibrium-index "-7 1 5 2 -4 3 0"
call :equilibrium-index "2 4 6"
call :equilibrium-index "2 9 2"
call :equilibrium-index "1 -1 1 -1 1 -1 1"
pause>nul
exit /b
%== The Function ==%
:equilibrium-index <sequence with quotes>
::Set the pseudo-array sequence...
set "seq=%~1"
set seq.length=0
for %%S in (!seq!) do (
set seq[!seq.length!]=%%S
set /a seq.length+=1
)
::Initialization of other variables...
set "equilms="
set /a last=seq.length - 1
::The main checking...
for /l %%e in (0,1,!last!) do (
set left=0
set right=0
for /l %%i in (0,1,!last!) do (
if %%i lss %%e (set /a left+=!seq[%%i]!)
if %%i gtr %%e (set /a right+=!seq[%%i]!)
)
if !left!==!right! (
if defined equilms (
set "equilms=!equilms! %%e"
) else (
set "equilms=%%e"
)
)
)
echo [!equilms!]
goto :EOF
%==/The Function ==%

View file

@ -0,0 +1,40 @@
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
template <typename T>
std::vector<size_t> equilibrium(T first, T last)
{
typedef typename std::iterator_traits<T>::value_type value_t;
value_t left = 0;
value_t right = std::accumulate(first, last, value_t(0));
std::vector<size_t> result;
for (size_t index = 0; first != last; ++first, ++index)
{
right -= *first;
if (left == right)
{
result.push_back(index);
}
left += *first;
}
return result;
}
template <typename T>
void print(const T& value)
{
std::cout << value << "\n";
}
int main()
{
const int data[] = { -7, 1, 5, 2, -4, 3, 0 };
std::vector<size_t> indices(equilibrium(data, data + 7));
std::for_each(indices.begin(), indices.end(), print<size_t>);
}

View file

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static IEnumerable<int> EquilibriumIndices(IEnumerable<int> sequence)
{
var left = 0;
var right = sequence.Sum();
var index = 0;
foreach (var element in sequence)
{
right -= element;
if (left == right)
{
yield return index;
}
left += element;
index++;
}
}
static void Main()
{
foreach (var index in EquilibriumIndices(new[] { -7, 1, 5, 2, -4, 3, 0 }))
{
Console.WriteLine(index);
}
}
}

View file

@ -0,0 +1,2 @@
3
6

View file

@ -0,0 +1,44 @@
#include <stdio.h>
#include <stdlib.h>
int list[] = {-7, 1, 5, 2, -4, 3, 0};
int eq_idx(int *a, int len, int **ret)
{
int i, sum, s, cnt;
/* alloc long enough: if we can afford the original list,
* we should be able to afford to this. Beats a potential
* million realloc() calls. Even if memory is a real concern,
* there's no garantee the result is shorter than the input anyway */
cnt = s = sum = 0;
*ret = malloc(sizeof(int) * len);
for (i = 0; i < len; i++)
sum += a[i];
for (i = 0; i < len; i++) {
if (s * 2 + a[i] == sum) {
(*ret)[cnt] = i;
cnt++;
}
s += a[i];
}
/* uncouraged way to use realloc since it can leak memory, for example */
*ret = realloc(*ret, cnt * sizeof(int));
return cnt;
}
int main()
{
int i, cnt, *idx;
cnt = eq_idx(list, sizeof(list) / sizeof(int), &idx);
printf("Found:");
for (i = 0; i < cnt; i++)
printf(" %d", idx[i]);
printf("\n");
return 0;
}

View file

@ -0,0 +1,8 @@
(defn equilibrium [lst]
(loop [acc '(), i 0, left 0, right (apply + lst), lst lst]
(if (empty? lst)
(reverse acc)
(let [[x & xs] lst
right (- right x)
acc (if (= left right) (cons i acc) acc)]
(recur acc (inc i) (+ left x) right xs)))))

View file

@ -0,0 +1,15 @@
(defun dflt-on-nil (v dflt)
(if v v dflt))
(defun eq-index (v)
(do*
((stack nil)
(i 0 (+ 1 i))
(rest v (cdr rest))
(lsum 0)
(rsum (apply #'+ (cdr v))))
;; Reverse here is not strictly necessary
((null rest) (reverse stack))
(if (eql lsum rsum) (push i stack))
(setf lsum (+ lsum (car rest)))
(setf rsum (- rsum (dflt-on-nil (cadr rest) 0)))))

View file

@ -0,0 +1,2 @@
(eq-index '(-7 1 5 2 -4 3 0))
(3 6)

View file

@ -0,0 +1,9 @@
import std.stdio, std.algorithm, std.range, std.functional;
auto equilibrium(Range)(Range r) pure nothrow @safe /*@nogc*/ {
return r.length.iota.filter!(i => r[0 .. i].sum == r[i + 1 .. $].sum);
}
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}

View file

@ -0,0 +1,18 @@
import std.stdio, std.algorithm;
size_t[] equilibrium(T)(in T[] items) @safe pure nothrow {
size_t[] result;
T left = 0, right = items.sum;
foreach (immutable i, e; items) {
right -= e;
if (right == left)
result ~= i;
left += e;
}
return result;
}
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
}

View file

@ -0,0 +1,21 @@
PROGRAM EQUILIBRIUM
DIM LISTA[6]
PROCEDURE EQ(LISTA[]->RES$)
LOCAL I%,R,S,E$
FOR I%=0 TO UBOUND(LISTA,1) DO
S+=LISTA[I%]
END FOR
FOR I%=0 TO UBOUND(LISTA,1) DO
IF R=S-R-LISTA[I%] THEN E$+=STR$(I%)+"," END IF
R+=LISTA[I%]
END FOR
RES$=LEFT$(E$,LEN(E$)-1)
END PROCEDURE
BEGIN
LISTA[]=(-7,1,5,2,-4,3,0)
EQ(LISTA[]->RES$)
PRINT("Equilibrium indices are";RES$)
END PROGRAM

View file

@ -0,0 +1,68 @@
import extensions;
import system'routines;
import system'collections;
import extensions'routines;
class EquilibriumEnumerator : Enumerator
{
int left;
int right;
int index;
Enumerator en;
constructor new(Enumerator en)
{
this en := en;
self.reset()
}
constructor new(Enumerable list)
<= new(list.enumerator());
constructor new(o)
<= new(cast Enumerable(o));
bool next()
{
index += 1;
while(en.next())
{
var element := en.get();
right -= element;
bool found := (left == right);
left += element;
if (found)
{
^ true
};
index += 1
};
^ false
}
reset()
{
en.reset();
left := 0;
right := en.summarize();
index := -1;
en.reset();
}
get() = index;
enumerable() => en;
}
public program()
{
EquilibriumEnumerator.new(new int[]{ -7, 1, 5, 2, -4, 3, 0 })
.forEach:printingLn
}

View file

@ -0,0 +1,8 @@
defmodule Equilibrium do
def index(list) do
last = length(list)
Enum.filter(0..last-1, fn i ->
Enum.sum(Enum.slice(list, 0, i)) == Enum.sum(Enum.slice(list, i+1..last))
end)
end
end

View file

@ -0,0 +1,7 @@
defmodule Equilibrium do
def index(list), do: index(list,0,0,Enum.sum(list),[])
defp index([],_,_,_,acc), do: Enum.reverse(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)
end

View file

@ -0,0 +1,9 @@
indices = [
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
[2, 9, 2],
[1,-1, 1,-1, 1,-1, 1]
]
Enum.each(indices, fn list ->
IO.puts "#{inspect list} => #{inspect Equilibrium.index(list)}"
end)

View file

@ -0,0 +1,20 @@
function equilibrium(sequence s)
integer lower_sum, higher_sum
sequence indices
lower_sum = 0
higher_sum = 0
for i = 1 to length(s) do
higher_sum += s[i]
end for
indices = {}
for i = 1 to length(s) do
higher_sum -= s[i]
if lower_sum = higher_sum then
indices &= i
end if
lower_sum += s[i]
end for
return indices
end function
? equilibrium({-7,1,5,2,-4,3,0})

View file

@ -0,0 +1,6 @@
USE: math.vectors
: accum-left ( seq id quot -- seq ) accumulate nip ; inline
: accum-right ( seq id quot -- seq ) [ <reversed> ] 2dip accum-left <reversed> ; inline
: equilibrium-indices ( seq -- inds )
0 [ + ] [ accum-left ] [ accum-right ] 3bi [ = ] 2map
V{ } swap dup length iota [ [ suffix ] curry [ ] if ] 2each ;

View file

@ -0,0 +1,2 @@
( scratchpad ) { -7 1 5 2 -4 3 0 } equilibrium-indices .
V{ 3 6 }

View file

@ -0,0 +1,19 @@
program Equilibrium
implicit none
integer :: array(7) = (/ -7, 1, 5, 2, -4, 3, 0 /)
call equil_index(array)
contains
subroutine equil_index(a)
integer, intent(in) :: a(:)
integer :: i
do i = 1, size(a)
if(sum(a(1:i-1)) == sum(a(i+1:size(a)))) write(*,*) i
end do
end subroutine
end program

View file

@ -0,0 +1,36 @@
' FB 1.05.0 Win64
Sub equilibriumIndices (a() As Integer, b() As Integer)
If UBound(a) = -1 Then Return '' empty array
Dim sum As Integer = 0
Dim count As Integer = 0
For i As Integer = LBound(a) To UBound(a) : sum += a(i) : Next
Dim sumLeft As Integer = 0, sumRight As Integer = 0
For i As Integer = LBound(a) To UBound(a)
sumRight = sum - sumLeft - a(i)
If sumLeft = sumRight Then
Redim Preserve b(0 To Count)
b(count) = i
count += 1
End If
sumLeft += a(i)
Next
End Sub
Dim a(0 To 6) As Integer = { -7, 1, 5, 2, -4, 3, 0 }
Dim b() As Integer
equilibriumIndices a(), b()
If UBound(b) = -1 Then
Print "There are no equilibrium indices"
ElseIf UBound(b) = LBound(b) Then
Print "The only equilibrium index is : "; b(LBound(b))
Else
Print "The equilibrium indices are : "
For i As Integer = LBound(b) To UBound(b) : Print b(i); " "; : Next
End If
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,36 @@
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println(ex([]int32{-7, 1, 5, 2, -4, 3, 0}))
// sequence of 1,000,000 random numbers, with values
// chosen so that it will be likely to have a couple
// of equalibrium indexes.
rand.Seed(time.Now().UnixNano())
verylong := make([]int32, 1e6)
for i := range verylong {
verylong[i] = rand.Int31n(1001) - 500
}
fmt.Println(ex(verylong))
}
func ex(s []int32) (eq []int) {
var r, l int64
for _, el := range s {
r += int64(el)
}
for i, el := range s {
r -= int64(el)
if l == r {
eq = append(eq, i)
}
l += int64(el)
}
return
}

View file

@ -0,0 +1,10 @@
import System.Random (randomRIO)
import Data.List (findIndices, takeWhile)
import Control.Monad (replicateM)
import Control.Arrow ((&&&))
equilibr xs =
findIndices (\(a, b) -> sum a == sum b) . takeWhile (not . null . snd) $
flip ((&&&) <$> take <*> (drop . pred)) xs <$> [1 ..]
langeSliert = replicateM 2000 (randomRIO (-15, 15) :: IO Int) >>= print . equilibr

View file

@ -0,0 +1,2 @@
*Main> equilibr [-7, 1, 5, 2, -4, 3, 0]
[3,6]

View file

@ -0,0 +1,2 @@
*Main> langeSliert
[231,245,259,265,382,1480,1611,1612]

View file

@ -0,0 +1,21 @@
equilibriumIndices :: [Int] -> [Int]
equilibriumIndices xs =
zip3
(scanl1 (+) xs) -- Sums from the left
(scanr1 (+) xs) -- Sums from the right
[0 ..] -- Indices
>>= (\(x, y, i) -> [i | x == y])
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
print
$ equilibriumIndices
<$> [ [-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
[2, 9, 2],
[1, -1, 1, -1, 1, -1, 1],
[1],
[]
]

View file

@ -0,0 +1,16 @@
procedure main(arglist)
L := if *arglist > 0 then arglist else [-7, 1, 5, 2, -4, 3, 0] # command line args or default
every writes( "equilibrium indicies of [ " | (!L ||" ") | "] = " | (eqindex(L)||" ") | "\n" )
end
procedure eqindex(L) # generate equilibrium points in a list L or fail
local s,l,i
every (s := 0, i := !L) do
s +:= numeric(i) | fail # sum and validate
every (l := 0, i := 1 to *L) do {
if l = (s-L[i])/2 then suspend i
l +:= L[i] # sum of left side
}
end

View file

@ -0,0 +1 @@
equilidx=: +/\ I.@:= +/\.

View file

@ -0,0 +1,2 @@
equilidx _7 1 5 2 _4 3 0
3 6

View file

@ -0,0 +1,23 @@
public class Equlibrium {
public static void main(String[] args) {
int[] sequence = {-7, 1, 5, 2, -4, 3, 0};
equlibrium_indices(sequence);
}
public static void equlibrium_indices(int[] sequence){
//find total sum
int totalSum = 0;
for (int n : sequence) {
totalSum += n;
}
//compare running sum to remaining sum to find equlibrium indices
int runningSum = 0;
for (int i = 0; i < sequence.length; i++) {
int n = sequence[i];
if (totalSum - runningSum - n == runningSum) {
System.out.println(i);
}
runningSum += n;
}
}
}

View file

@ -0,0 +1,19 @@
function equilibrium(a) {
var N = a.length, i, l = [], r = [], e = []
for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i<N; i++)
l[i] = l[i - 1] + a[i], r[N - i - 1] = r[N - i] + a[N - i - 1]
for (i = 0; i < N; i++)
if (l[i] === r[i]) e.push(i)
return e
}
// test & output
[ [-7, 1, 5, 2, -4, 3, 0], // 3, 6
[2, 4, 6], // empty
[2, 9, 2], // 1
[1, -1, 1, -1, 1, -1, 1], // 0,1,2,3,4,5,6
[1], // 0
[] // empty
].forEach(function(x) {
console.log(equilibrium(x))
});

View file

@ -0,0 +1 @@
[[3,6],[],[1],[0,1,2,3,4,5,6],[0],[]]

View file

@ -0,0 +1,16 @@
function equilibrium(arr) {
let sum = arr.reduce((a, b) => a + b);
let leftSum = 0;
for (let i = 0; i < arr.length; ++i) {
sum -= arr[i];
if (leftSum === sum) {
return i;
}
leftSum += arr[i];
}
return -1;
}

View file

@ -0,0 +1 @@
3, -1, 1, 0, 0

View file

@ -0,0 +1,109 @@
(() => {
"use strict";
// ------------- ALL EQUILIBRIUM INDICES -------------
// equilibriumIndices :: [Int] -> [Int]
const equilibriumIndices = xs =>
zip(
scanl1(add)(xs)
)(
scanr1(add)(xs)
)
.reduceRight(
(a, xy, i) => xy[0] === xy[1] ? (
[i, ...a]
) : a, []
);
// ---------------------- TEST -----------------------
const main = () => [
[-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
[2, 9, 2],
[1, -1, 1, -1, 1, -1, 1],
[1],
[]
].map(compose(
JSON.stringify,
equilibriumIndices
))
.join("\n");
// -> [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []]
// ---------------- GENERIC FUNCTIONS ----------------
// add (+) :: Num a => a -> a -> a
const add = a =>
// 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 =>
// The series of interim values arising
// from a catamorphism. Parallel to foldl.
xs.reduce((a, x) => {
const v = f(a[0])(x);
return [v, a[1].concat(v)];
}, [startValue, [startValue]])[1];
// scanl1 :: (a -> a -> a) -> [a] -> [a]
const scanl1 = f =>
// scanl1 is a variant of scanl that has no
// starting value argument.
xs => xs.length > 0 ? (
scanl(f)(
xs[0]
)(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]
const scanr1 = f =>
// scanr1 is a variant of scanr that has no
// seed-value argument, and assumes that
// xs is not empty.
xs => xs.length > 0 ? (
scanr(f)(
xs.slice(-1)[0]
)(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) => [xs[i], ys[i]]);
// MAIN ---
return main();
})();

View file

@ -0,0 +1,9 @@
# The index origin is 0 in jq.
def equilibrium_indices:
. as $in
| add as $add
| foreach range(0;length) as $i (
[0, 0, $add]; # [before, pivot, after]
$in[$i] as $x | [.[0]+.[1], $x, .[2] - $x];
if .[0] == .[2] then $i else empty end) ;

View file

@ -0,0 +1 @@
[-7, 1, 5, 2, -4, 3, 0] | equilibrium_indices

View file

@ -0,0 +1,6 @@
def count(g): reduce g as $i (0; .+1);
# Create an array of length n with "init" elements:
def array(n;init): reduce range(0;n) as $i ([]; . + [0]);
count( array(10000;0) | equilibrium_indices )

View file

@ -0,0 +1,17 @@
function equindex2pass(data::Array)
rst = Vector{Int}(0)
suml, sumr, ddelayed = 0, sum(data), 0
for (i, d) in enumerate(data)
suml += ddelayed
sumr -= d
ddelayed = d
if suml == sumr
push!(rst, i)
end
end
return rst
end
@show equindex2pass([1, -1, 1, -1, 1, -1, 1])
@show equindex2pass([1, 2, 2, 1])
@show equindex2pass([-7, 1, 5, 2, -4, 3, 0])

View file

@ -0,0 +1,13 @@
f:{&{(+/y# x)=+/(y+1)_x}[x]'!#x}
f -7 1 5 2 -4 3 0
3 6
f 2 4 6
!0
f 2 9 2
,1
f 1 -1 1 -1 1 -1 1
0 1 2 3 4 5 6

View file

@ -0,0 +1,25 @@
// version 1.1
fun equilibriumIndices(a: IntArray): MutableList<Int> {
val ei = mutableListOf<Int>()
if (a.isEmpty()) return ei // empty list
val sumAll = a.sumBy { it }
var sumLeft = 0
var sumRight: Int
for (i in 0 until a.size) {
sumRight = sumAll - sumLeft - a[i]
if (sumLeft == sumRight) ei.add(i)
sumLeft += a[i]
}
return ei
}
fun main(args: Array<String>) {
val a = intArrayOf(-7, 1, 5, 2, -4, 3, 0)
val ei = equilibriumIndices(a)
when (ei.size) {
0 -> println("There are no equilibrium indices")
1 -> println("The only equilibrium index is : ${ei[0]}")
else -> println("The equilibrium indices are : ${ei.joinToString(", ")}")
}
}

View file

@ -0,0 +1,26 @@
a(0)=-7
a(1)=1
a(2)=5
a(3)=2
a(4)=-4
a(5)=3
a(6)=0
print "EQ Indices are ";EQindex$("a",0,6)
wait
function EQindex$(b$,mini,maxi)
if mini>=maxi then exit function
sum=0
for i = mini to maxi
sum=sum+eval(b$;"(";i;")")
next
sumA=0:sumB=sum
for i = mini to maxi
sumB = sumB - eval(b$;"(";i;")")
if sumA=sumB then EQindex$=EQindex$+str$(i)+", "
sumA = sumA + eval(b$;"(";i;")")
next
if len(EQindex$)>0 then EQindex$=mid$(EQindex$, 1, len(EQindex$)-2) 'remove last ", "
end function

View file

@ -0,0 +1,10 @@
to equilibrium.iter :i :before :after :tail :ret
if equal? :before :after [make "ret lput :i :ret]
if empty? butfirst :tail [output :ret]
output equilibrium.iter :i+1 (:before+first :tail) (:after-first butfirst :tail) (butfirst :tail) :ret
end
to equilibrium.index :list
output equilibrium.iter 1 0 (apply "sum butfirst :list) :list []
end
show equilibrium_index [-7 1 5 2 -4 3 0] ; [4 7]

View file

@ -0,0 +1,22 @@
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}))

View file

@ -0,0 +1,11 @@
function indicies = equilibriumIndex(list)
indicies = [];
for i = (1:numel(list))
if ( sum(-list(1:i)) == sum(-list(i:end)) )
indicies = [indicies i];
end
end
end

View file

@ -0,0 +1,5 @@
>> equilibriumIndex([-7 1 5 2 -4 3 0])
ans =
4 7

View file

@ -0,0 +1,3 @@
equilibriumIndex[data_]:=Reap[
Do[If[Total[data[[;; n - 1]]] == Total[data[[n + 1 ;;]]],Sow[n]],
{n, Length[data]}]][[2, 1]]

View file

@ -0,0 +1,36 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 20
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- @see http://www.geeksforgeeks.org/equilibrium-index-of-an-array/
method equilibriumIndex(sequence) private static
es = ''
loop ix = 1 to sequence.words()
sum = 0
loop jx = 1 to sequence.words()
if jx < ix then sum = sum + sequence.word(jx)
if jx > ix then sum = sum - sequence.word(jx)
end jx
if sum = 0 then es = es ix
end ix
return es
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
-- Note: A Rexx object based list of "words" starts at index 1
sequences = [ -
'-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
]
loop sequence over sequences
say 'For sequence "'sequence.space(1, ',')'" the equilibrium indices are: \-'
say '"'equilibriumIndex(sequence).space(1, ',')'"'
end sequence
return

View file

@ -0,0 +1,20 @@
import math, sequtils, strutils
iterator eqindex(data: openArray[int]): int =
var suml, ddelayed = 0
var sumr = sum(data)
for i,d in data:
suml += ddelayed
sumr -= d
ddelayed = d
if suml == sumr:
yield i
const d = @[@[-7, 1, 5, 2, -4, 3, 0],
@[2, 4, 6],
@[2, 9, 2],
@[1, -1, 1, -1, 1, -1, 1]]
for data in d:
echo "d = [", data.join(", "), ']'
echo "eqIndex(d) -> [", toSeq(eqindex(data)).join(", "), ']'

View file

@ -0,0 +1,15 @@
let lst = [ -7; 1; 5; 2; -4; 3; 0 ]
let sum = List.fold_left ( + ) 0 lst
let () =
let rec aux acc i left right = function
| x::xs ->
let right = right - x in
let acc = if left = right then i::acc else acc in
aux acc (succ i) (left + x) right xs
| [] -> List.rev acc
in
let res = aux [] 0 0 sum lst in
print_string "Results:";
List.iter (Printf.printf " %d") res;
print_newline ()

View file

@ -0,0 +1,24 @@
class Rosetta {
function : Main(args : String[]) ~ Nil {
sequence := [-7, 1, 5, 2, -4, 3, 0];
EqulibriumIndices(sequence);
}
function : EqulibriumIndices(sequence : Int[]) ~ Nil {
# find total sum
totalSum := 0;
each(i : sequence) {
totalSum += sequence[i];
};
# compare running sum to remaining sum to find equlibrium indices
runningSum := 0;
each(i : sequence) {
n := sequence[i];
if (totalSum - runningSum - n = runningSum) {
i->PrintLine();
};
runningSum += n;
};
}
}

View file

@ -0,0 +1,9 @@
: equilibrium(l)
| ls rs i e |
0 ->ls
l sum ->rs
ListBuffer new l size loop: i [
l at(i) ->e
rs e - dup ->rs ls == ifTrue: [ i over add ]
ls e + ->ls
] ;

View file

@ -0,0 +1,9 @@
equilib(v)={
my(a=sum(i=2,#v,v[i]),b=0,u=[]);
for(i=1,#v-1,
if(a==b, u=concat(u,i));
b+=v[i];
a-=v[i+1]
);
if(b,u,concat(u,#v))
};

View file

@ -0,0 +1,18 @@
<?php
$arr = array(-7, 1, 5, 2, -4, 3, 0);
function getEquilibriums($arr) {
$right = array_sum($arr);
$left = 0;
$equilibriums = array();
foreach($arr as $key => $value){
$right -= $value;
if($left == $right) $equilibriums[] = $key;
$left += $value;
}
return $equilibriums;
}
echo "# results:\n";
foreach (getEquilibriums($arr) as $r) echo "$r, ";
?>

View file

@ -0,0 +1,36 @@
Program EquilibriumIndexDemo(output);
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
function ArraySum(list: array of integer; first, last: integer): integer;
var
i: integer;
begin
Result := 0;
for i := first to last do // not taken if first > last
Result := Result + list[i];
end;
procedure EquilibriumIndex(list: array of integer; offset: integer);
var
i: integer;
begin
for i := low(list) to high(list) do
if ArraySum(list, low(list), i-1) = ArraySum(list, i+1, high(list)) then
write(offset + i:3);
end;
var
{** The base index of the array is fully taken care off and can be any number. **}
numbers: array [1..7] of integer = (-7, 1, 5, 2, -4, 3, 0);
i: integer;
begin
write('List of numbers: ');
for i := low(numbers) to high(numbers) do
write(numbers[i]:3);
writeln;
write('Equilibirum indices: ');
EquilibriumIndex(numbers, low(numbers));
writeln;
end.

View file

@ -0,0 +1,86 @@
Program EquilibriumIndexDemo(output);
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
type
tEquiData = shortInt;//Int64;extended ,double
tnumList = array of tEquiData;
tresList = array of LongInt;
const
cNumbers: array [11..17] of tEquiData = (-7, 1, 5, 2, -4, 3, 0);
function ArraySum(const list: tnumList):tEquiData;
var
i: integer;
begin
result := 0;
for i := Low(list) to High(list) do
result := result+list[i];
end;
procedure EquilibriumIndex(const list:tnumList;
var indices:tresList);
var
pC : ^tEquiData;
LeftSum,
RightSum : tEquiData;
i,idx,HiList: integer;
begin
HiList := High(List);
RightSum :=ArraySum(list);
setlength(indices,10);
idx := 0;
i := -Hilist;
pC := @List[0];
LeftSum:= 0;
repeat
Rightsum:= RightSum-pC^;
IF LeftSum = RightSum then
Begin
indices[idx] := Hilist+i;
inc(idx);
IF idx > high(indices) then
setlength(indices, idx+10);
end;
inc(i);
leftSum := leftsum+pC^;
inc(pC);
until i>=0;
leftSum := leftsum+pC^;
IF LeftSum = RightSum then
Begin
indices[idx] := Hilist+i;
inc(idx);
end;
setlength(indices,idx);
end;
procedure TestRun(const numbers:tnumList);
var
indices : tresList;
i: integer;
Begin
write('List of numbers: ');
for i := low(numbers) to high(numbers) do
write(numbers[i]:3);
writeln;
EquilibriumIndex(numbers,indices);
write('Equilibirum indices: ');
EquilibriumIndex(numbers,indices);
for i := low(indices) to high(indices) do
write(indices[i]:3);
writeln;
writeln;
end;
var
numbers: tnumList;
I: integer;
begin
setlength(numbers,High(cNumbers)-Low(cNumbers)+1);
move(cNumbers[Low(cNumbers)],numbers[0],sizeof(cnumbers));
TestRun(numbers);
for i := low(numbers) to high(numbers) do
numbers[i]:= 0;
TestRun(numbers);
end.

View file

@ -0,0 +1,15 @@
sub eq_index {
my ( $i, $sum, %sums ) = ( 0, 0 );
for (@_) {
push @{ $sums{ $sum * 2 + $_ } }, $i++;
$sum += $_;
}
return join ' ', @{ $sums{$sum} || [] }, "\n";
}
print eq_index qw( -7 1 5 2 -4 3 0 ); # 3 6
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

View file

@ -0,0 +1,18 @@
(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>
<!--

View file

@ -0,0 +1,4 @@
equilibrium_index1(A, Ix) =>
append(Front, [_|Back], A),
sum(Front) = sum(Back),
Ix = length(Front)+1. % give 1 based index

View file

@ -0,0 +1,13 @@
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.

View file

@ -0,0 +1,32 @@
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.

View file

@ -0,0 +1,6 @@
(de equilibria (Lst)
(make
(let Sum 0
(for ((I . L) Lst L (cdr L))
(and (= Sum (sum prog (cdr L))) (link I))
(inc 'Sum (car L)) ) ) ) )

View file

@ -0,0 +1,22 @@
function Get-EquilibriumIndex ( $Sequence )
{
$Indexes = 0..($Sequence.Count - 1)
$EqulibriumIndex = @()
ForEach ( $TestIndex in $Indexes )
{
$Left = 0
$Right = 0
ForEach ( $Index in $Indexes )
{
If ( $Index -lt $TestIndex ) { $Left += $Sequence[$Index] }
ElseIf ( $Index -gt $TestIndex ) { $Right += $Sequence[$Index] }
}
If ( $Left -eq $Right )
{
$EqulibriumIndex += $TestIndex
}
}
return $EqulibriumIndex
}

View file

@ -0,0 +1 @@
Get-EquilibriumIndex -7, 1, 5, 2, -4, 3, 0

View file

@ -0,0 +1,6 @@
equilibrium_index(List, Index) :-
append(Front, [_|Back], List),
sumlist(Front, Sum),
sumlist(Back, Sum),
length(Front, Len),
Index is Len.

View file

@ -0,0 +1,4 @@
?- equilibrium_index([-7, 1, 5, 2, -4, 3, 0], Index).
Index = 3 ;
Index = 6 ;
false.

View file

@ -0,0 +1,14 @@
If OpenConsole()
Define i, c=CountProgramParameters()-1
For i=0 To c
Define j, LSum=0, RSum=0
For j=0 To c
If j<i
LSum+Val(ProgramParameter(j))
ElseIf j>i
RSum+Val(ProgramParameter(j))
EndIf
Next j
If LSum=RSum: PrintN(Str(i)): EndIf
Next i
EndIf

View file

@ -0,0 +1,9 @@
def eqindex2Pass(data):
"Two pass"
suml, sumr, ddelayed = 0, sum(data), 0
for i, d in enumerate(data):
suml += ddelayed
sumr -= d
ddelayed = d
if suml == sumr:
yield i

View file

@ -0,0 +1,6 @@
def eqindexMultiPass(data):
"Multi pass"
for i in range(len(data)):
suml, sumr = sum(data[:i]), sum(data[i+1:])
if suml == sumr:
yield i

View file

@ -0,0 +1,4 @@
def eqindexMultiPass(s):
return [i for i in xrange(len(s)) if sum(s[:i]) == sum(s[i+1:])]
print eqindexMultiPass([-7, 1, 5, 2, -4, 3, 0])

View file

@ -0,0 +1,9 @@
from collections import defaultdict
def eqindex1Pass(data):
"One pass"
l, h = 0, defaultdict(list)
for i, c in enumerate(data):
l += c
h[l * 2 - c].append(i)
return h[l]

View file

@ -0,0 +1,10 @@
f = (eqindex2Pass, eqindexMultiPass, eqindex1Pass)
d = ([-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
[2, 9, 2],
[1, -1, 1, -1, 1, -1, 1])
for data in d:
print("d = %r" % data)
for func in f:
print(" %16s(d) -> %r" % (func.__name__, list(func(data))))

View file

@ -0,0 +1,65 @@
"""Equilibrium index"""
from itertools import (accumulate)
# equilibriumIndices :: [Num] -> [Int]
def equilibriumIndices(xs):
'''List indices at which the sum of values to the left
equals the sum of values to the right.
'''
def go(xs):
'''Left scan from accumulate,
right scan derived from left
'''
ls = list(accumulate(xs))
n = ls[-1]
return [
i for (i, (x, y)) in enumerate(zip(
ls,
[n] + [n - x for x in ls[0:-1]]
)) if x == y
]
return go(xs) if xs else []
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Tabulated test results'''
print(
tabulated('Equilibrium indices:\n')(
equilibriumIndices
)([
[-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
[2, 9, 2],
[1, -1, 1, -1, 1, -1, 1],
[1],
[]
])
)
# ----------------------- GENERIC ------------------------
# tabulated :: String -> (a -> b) -> [a] -> String
def tabulated(s):
'''heading -> function -> input List
-> tabulated output string
'''
def go(f):
def width(x):
return len(str(x))
def cols(xs):
w = width(max(xs, key=width))
return s + '\n' + '\n'.join([
str(x).rjust(w, ' ') + ' -> ' + str(f(x))
for x in xs
])
return cols
return go
if __name__ == '__main__':
main()

View file

@ -0,0 +1,14 @@
[ 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

View file

@ -0,0 +1,17 @@
/*REXX program calculates and displays the equilibrium index for a numeric array (list).*/
parse arg x /*obtain the optional arguments from CL*/
if x='' then x= copies(" 7 -7", 50) 7 /*Not specified? Then use the default.*/
say ' array list: ' space(x) /*echo the array list to the terminal. */
#= words(x) /*the number of elements in the X list.*/
do j=0 for #; @.j= word(x, j+1) /*zero─start is for zero─based array. */
end /*j*/ /* [↑] assign @.0 @.1 @.3 ··· */
say /* ··· and also display a blank line. */
answer= equilibriumIDX(); w= words(answer) /*calculate the equilibrium index. */
say 'equilibrium' word("(none) index: indices:", 1 + (w>0) + (w>1)) answer
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
equilibriumIDX: $=; do i=0 for #; sum= 0
do k=0 for #; sum= sum + @.k * sign(k-i); end /*k*/
if sum==0 then $= $ i
end /*i*/ /* [↑] Zero? Found an equilibrium index*/
return $ /*return equilibrium list (may be null)*/

View file

@ -0,0 +1,33 @@
/* REXX ---------------------------------------------------------------
* 30.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
parse arg l
say ' array list:' strip(l)
x.=0
Do i=1 To words(l)
x.i=word(l,i)
End
n=i-1
ans=strip(equilibriumIndices())
n=words(ans)
Select
When n=0 Then Say 'There''s no equilibrium index'
When n=1 Then Say 'equilibrium index :' ans
Otherwise Say 'equilibrium indices:' ans
End
Say '---'
exit
equilibriumIndices: procedure expose x. n
sum.=0
sum=0
eil=''
Do i=1 To n
sum=sum+x.i
sum.i=sum
End
Do i=1 To n
im1=i-1
If sum.im1=(sum.n-x.i)/2 Then
eil=eil im1
End
Return eil

View file

@ -0,0 +1,15 @@
#lang racket
(define (subsums xs)
(for/fold ([sums '()] [sum 0]) ([x xs])
(values (cons (+ x sum) sums)
(+ x sum))))
(define (equivilibrium xs)
(define-values (sums total) (subsums xs))
(for/list ([sum (reverse sums)]
[x xs]
[i (in-naturals)]
#:when (= (- sum x) (- total sum)))
i))
(equivilibrium '(-7 1 5 2 -4 3 0))

View file

@ -0,0 +1 @@
'(3 6)

View file

@ -0,0 +1,12 @@
sub equilibrium_index(@list) {
my ($left,$right) = 0, [+] @list;
gather for @list.kv -> $i, $x {
$right -= $x;
take $i if $left == $right;
$left += $x;
}
}
my @list = -7, 1, 5, 2, -4, 3, 0;
.say for equilibrium_index(@list).grep(/\d/);

View file

@ -0,0 +1,5 @@
sub equilibrium_index(@list) {
my @a = [\+] @list;
my @b = reverse [\+] reverse @list;
^@list Zxx (@a »==« @b);
}

View file

@ -0,0 +1,5 @@
# Original example, with expanded calculations:
0 1 2 3 4 5 6 # Index
-7 1 5 2 -4 3 0 # C (Value at index)
0 -7 -6 -1 1 -3 0 # L (Sum of left)
-7 -13 -7 0 -2 -3 0 # 2L+C

Some files were not shown because too many files have changed in this diff Show more