Logo

Programming-Idioms

History of Idiom 195 > diff from v8 to v9

Edit summary for version 9 by programming-idioms.org:
[Rust] +DocURL

Version 8

2021-06-09, 10:32:27

Version 9

2021-06-20, 15:37:58

Idiom #195 Pass a two-dimensional array

Pass an array a of real numbers to the procedure (resp. function) foo. Output the size of the array, and the sum of all its elements when each element is multiplied with the array indices i and j (assuming they start from one).

Idiom #195 Pass a two-dimensional array

Pass an array a of real numbers to the procedure (resp. function) foo. Output the size of the array, and the sum of all its elements when each element is multiplied with the array indices i and j (assuming they start from one).

Variables
a,foo,i,j
Variables
a,foo,i,j
Imports
#[macro_use] extern crate itertools;
Imports
#[macro_use] extern crate itertools;
Code
fn foo(a: Vec<Vec<usize>>) {
    println!(
        "Length of array: {}",
        a.clone()
            .into_iter()
            .flatten()
            .collect::<Vec<usize>>()
            .len()
    );

    let mut sum = 0;
    for (i, j) in izip!(&a[0], &a[1]) {
        sum += i * j
    }

    println!("Sum of all products of indices: {}", sum);
}
Code
fn foo(a: Vec<Vec<usize>>) {
    println!(
        "Length of array: {}",
        a.clone()
            .into_iter()
            .flatten()
            .collect::<Vec<usize>>()
            .len()
    );

    let mut sum = 0;
    for (i, j) in izip!(&a[0], &a[1]) {
        sum += i * j
    }

    println!("Sum of all products of indices: {}", sum);
}
Comments bubble
By useing izp! macro we can chain itteration over elements of array a
Comments bubble
By useing izip! macro we can chain itteration over elements of array a
Doc URL
https://docs.rs/itertools/0.7.8/itertools/macro.izip.html
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3b8467a7c42791a253439d3a6e06db11
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3b8467a7c42791a253439d3a6e06db11