Struct closest_sum_pair::Elements[][src]

pub struct Elements<'list> { /* fields omitted */ }
Expand description

This struct holds 5 pieces of information related to the list.

1.list: A mutable ref to a Vec<i32>.

2.len: Length of the vector.

3.desired_sum: This is a value that users will provide. This is the target value for the pairs.

4.pair: Pair that has the closest sum to desired_sum.

5.init_distance: Initialize the distance to number that is always greater than sum of any two numbers in list - desired sum.

Implementations

Returns an instance of Elements.

Examples

use closest_sum_pair::Elements;

let mut list: Vec<i32> = vec![3 ,5, 7];

let len: usize = list.len();

let desired_sum: i32 = 9;

let elements = Elements::new(&mut list, len, desired_sum);

Sorts the list in ascending order. We used rust’s builtin sort method for this.

As we need a value to initialize distance variable with, we need to figure out the smallest number possible for this. This initial value will have no connection with the list, so it has to be overwritten on very first comparison.

The find_pair method tries to minimize the distance on every comparison. So if the number is big enough, it will be replaced with a shorter distance value for any pair that comes first. Here, distance = paired sum - desired sum.

This method uses a simple algorithm to find a number that meets the criteria.

This method runs a loop and tries to minimize the distance for every comparison between current distance and sum of two numbers in list. It always doesn’t check all pairs, rather it breaks from the loop and returns from the function when desired_sum is found, otherwise it will check for every possibilities and return the closest sum.

We need to chain sort_list, find_init_distance, find_pair and result methods. The result method returns the pair.

Examples

use closest_sum_pair::Elements;

let mut list: Vec<i32> = vec![-2, -4, -7, -2, -5, -13, -7];

let len: usize = list.len();

let desired_sum: i32 = -1;

let mut elements = Elements::new(&mut list, len, desired_sum);

let pair: (i32, i32) = elements
    .sort_list()
    .find_init_distance()
    .find_pair()
    .result();

assert_eq!((-2, -2), pair);

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.