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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Equilibrium index step by step in the Rust 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 Rust programming language

Source code in the rust programming language

extern crate num;

use num::traits::Zero;

fn equilibrium_indices(v: &[i32]) -> Vec<usize> {
    let mut right = v.iter().sum();
    let mut left = i32::zero();

    v.iter().enumerate().fold(vec![], |mut out, (i, &el)| {
        right -= el;
        if left == right {
            out.push(i);
        }
        left += el;

        out
    })
}

fn main() {
    let v = [-7i32, 1, 5, 2, -4, 3, 0];
    let indices = equilibrium_indices(&v);
    println!("Equilibrium indices for {:?} are: {:?}", v, indices);
}


  

You may also check:How to resolve the algorithm Date manipulation step by step in the NetRexx programming language
You may also check:How to resolve the algorithm CSV to HTML translation step by step in the ML/I programming language
You may also check:How to resolve the algorithm Align columns step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Collections step by step in the Elena programming language
You may also check:How to resolve the algorithm Factorial step by step in the Arturo programming language