How to resolve the algorithm Equilibrium index step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Equilibrium index step by step in the OCaml programming language

Table of Contents

Problem Statement

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

A

{\displaystyle A}

: 3   is an equilibrium index, because: 6   is also an equilibrium index, because: (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence

A

{\displaystyle A}

.

Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Equilibrium index step by step in the OCaml programming language

Source code in the ocaml programming language

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 ()


  

You may also check:How to resolve the algorithm Date manipulation step by step in the FunL programming language
You may also check:How to resolve the algorithm 21 game step by step in the rust programming language
You may also check:How to resolve the algorithm Almost prime step by step in the Futhark programming language
You may also check:How to resolve the algorithm Anagrams step by step in the Vedit macro language programming language
You may also check:How to resolve the algorithm Stack traces step by step in the BASIC programming language