I am using reduce to replace the nonlinear loop in the code instead of the for statement.