Polyglot CheatSheet - Math

Updated: 2021-11-19

Sum of Array

Javascript

Use .reduce():

> a = [1, 2, 3, 4]
[ 1, 2, 3, 4 ]
> a.reduce((x, y) => x + y)
10

The full signature is:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

However only total and currentValue are required.

Cumulative Sum

Javascript

> const cumSum = [];
> [1, 2, 3, 4].reduce((a, b, i) => (cumSum[i] = a + b), 0);
> cumSum
[1, 3, 6, 10]

Max/Min/Mean

Hack

Math\max()
Math\min()
Math\mean()

Round

Java

Integer.valueOf(Math.round(value));

Log

Java

These 2 are equivalent:

Math.log1p(x)
Math.log(x+1)

Mod

  • C++/Java: if you directly calculate -4 % 3 you will get -1. You can use function: a % b = (a % b + b) % b to make it is a non negative integer.
  • Python: you can directly use -1 % 3, you will get 2 automatically.