Logo

Programming-Idioms

  • Python
  • Rust
  • Rust

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

#[macro_use] extern crate itertools;
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);
}

By useing izip! macro we can chain itteration over elements of array a
def foo(a):
    print(len(a))
    print(sum(
        x*(i+1) + y*(i+1)*2 for i, (x, y) in enumerate(a)
    ))
from functools import reduce
from operator import mul
from itertools import starmap
def foo(a):
    z, f = 0, lambda a, b: a + (i * b)
    for i, x in enumerate(a, 1):
        x = starmap(mul, enumerate(x, 1))
        z = z + reduce(f, x, 0)
    print(len(a), z)
foo(a)
def foo(a):
    z = 0
    for i, x in enumerate(a, 1):
        for j, y in enumerate(x, 1):
          # z = z + (y * i) + (y * j)
            z = z + (y * i * j)
    print(len(a), z)
foo(a)
subroutine foo(a)
  implicit none
  real, dimension(:,:) :: a
  real :: s
  integer :: i,j
  print *,size(a,1), size(a,2)
  s = 0
  do j=1,size(a,2)
    do i=1,size(a,1)
      s = s + a(i,j) * i * j
    end do
  end do
  print *,s
end subroutine foo
!
  call foo(a)

This is an assumed-shape array. The compiler automatically passes the bounds.

New implementation...
< >
tkoenig