Logo

Programming-Idioms

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

Idiom #208 Formula with arrays

Given the arrays a,b,c,d of equal length and the scalar e, calculate a = e*(a+b*c+cos(d)).
Store the results in a.

for i in 0..a.len() {
    a[i] = e * (a[i] + b[i] * c[i] + d[i].cos());
}
#include <math.h>
  for (i=0; i<n; i++)
    a[i] = e*(a[i]+b[i]*c[i]+cos(d[i]);
a = e*(a+b*c+cos(d))
import "math"
func applyFormula(a, b, c, d []float64, e float64) {
	for i, v := range a {
		a[i] = e * (v + b[i] + c[i] + math.Cos(d[i]))
	}
}
a.forEach((aa, i) => a[i] = e * (aa + b[i] * c[i] + Math.cos(d[i])))
import static java.lang.Math.cos;
import static java.util.stream.IntStream.range;
range(0, a.length)
    .forEach(i -> {
        a[i] = e * (a[0] + (b[1] * c[2]) + cos(d[3]));
    });
import static java.lang.Math.cos;
int i, n = a.length;
for (i = 0; i < n; ++i)
    a[i] = e * (a[0] + (b[1] * c[2]) + cos(d[3]));
for i := 0 to High(a) do
    a[i] = e*(a[i]+b[i]*c[i]+cos(d[i]);
$a[$_] = $e * ($a[$_] + $b[$_] * $c[$_] + cos $d[$_]) for 0 .. $#a;
import math
for i in xrange(len(a)):
	a[i] = e*(a[i] + b[i] + c[i] + math.cos(a[i]))
import math
a = [e*(a[i] + b[i] + c[i] + math.cos(d[i])) for i in range(len(a))]
from math import cos
f = lambda a, b, c, d: \
    e * (a + (b * c) + cos(d))
a = list(map(f, a, b, c, d))
from math import cos
def f(a, b, c, d):
    return e * (a + (b * c) + cos(d))
a = list(map(f, a, b, c, d))
a = a.zip(b,c,d).map{|i,j,k,l| e*(i+j*k+Math::cos(l)) }

New implementation...
< >
tkoenig