Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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

use List::Util qw(max);
sub foo {
    my ($A) = @_;
    my $i_size = @$A;
    my $j_size = max map { 0 + @$_ } @$A;
    printf "dimensions: %d %d\n", $i_size, $j_size;

    my $s;
    for my $i (1 .. $i_size) {
        for my $j (1 .. $j_size) {
            $s += $A->[$i - 1][$j - 1] * $i * $j;
        }
    }
    printf "sum: %f\n", $s;
}
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)
import "fmt"
func foo(a [][]int) {
	fmt.Println("array is ", len(a)[0], " x ", len(a))
	x := 0
	for i, v1 := range a {
		for j, v2 := range v1 {
			x += v2*(i+1)*(j+1)
		}
	}
	fmt.Println("result: ", x)
}
/**
 * @param {Array<Array>} arry
 *
 * @return {Array<Array>}
 */
function foo(arry) {
  let len = 0;
  let sum = 0;

  arry.forEach(function(base, i) {
    len += base.length;

    base.forEach(function(a, j) {
      sum += a * (i + 1) * (j + 1);
    });
  });

  console.log('Array size:', arry.length, ',', len);

  return sum;
}

foo(arry2d);
public static void foo(int[][] a){
       System.out.println("Array a has a size of " + a.length+" by " + a[0].length);
       int sum = 0;
       for (int i = 0; i<a.length; i++){
           for (int j = 0; j<a[0].length; j++){
               sum += ((i+1)*(j+1)*a[i][j]);
           }
       }
       System.out.println("The sum of all elements multiplied by their indices is: " + sum);
    }
import static java.lang.System.out;
void foo(double a[][]) {
    int i, j, m = a.length, n;
    double z = 0, t;
    out.println(m);
    for (i = 0; i < m; ++i) {
        n = a[i].length;
        for (j = 0; j < n; ++j) {
            z = (z + ((t = a[i][j]) * (i + 1)));
            z = (z + (t * (j + 1)));
        }
    }
    out.println(z);
}
procedure foo(a: array of double);
var
  sum: double;
  i: Integer;
begin
  for i := low(a) to high(a) do
    sum := sum + (i+1)*a[i];
  writeln('Size = ',Length(a),', Sum = ',sum:6:5);
end;

...
  foo(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)
def foo(ar)
  puts "Array size: #{ar.size}, #{ar.max.size}."
  ar.each.with_index(1).sum do |a, i|
    a.each.with_index(1).sum do |el, j|
      el*i*j
    end
  end
end

puts foo(array)
#[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);
}

New implementation...
< >
tkoenig