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).
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)
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);
...
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;
}
def foo(a):
print(len(a))
print(sum(
x*(i+1) + y*(i+1)*2 for i, (x, y) in enumerate(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)
Do you know the best way to do this in your language ?
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)
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(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)