replace for loop by reduce
Functionalize by replacing for by map