It is funny that our development team held a small-scale coding challenge. The challenge question is like:

Take an array of the form:

[[1, 4, 6, …],

[3, 6, …],

[1, 1, 8, 5, …]]and sum each row, then multiply these sums. For example above the expected result would be (1+4+6) * (3+6) * (1+1+8+5)

[1, 1, 8, 5, …]]and sum each row, then multiply these sums. For example above the expected result would be (1+4+6) * (3+6) * (1+1+8+5)

It is free to choose any programming language to solve that. Here is my answer: (Using PHP)

<?php

$array = array(

array(1,2,3,4),

array(3,2,8),

array(4,6)

);function add($a,$b){

return $a+$b;

}

function multiply($a,$b){

return $a*$b;

}

$array = array(

array(1,2,3,4),

array(3,2,8),

array(4,6)

);function add($a,$b){

return $a+$b;

}

function multiply($a,$b){

return $a*$b;

}

function run($arr){

$return_arr=array();

$return_arr = array_map(function($row){

return array_reduce($row,”add”);

},$arr);

return array_reduce($return_arr,”multiply”,1);

}

echo run($array);

?>

Basically, I used array_map to apply callback to each of the elements in the original array in order to get the sum-up result for each row. During this process, I applied array_reduce() which can reduce the array to a single value using a callback function “add”.

After that I should get an array which stores the sum-up result for each row. For example, if the original array is [[1,2,3],[3,5],[7,3]], then at the end of this stage, we can get the outcome like [6,8,10].

Then the rest task is to multiply iteratively for this array. So, what I did was using array_reduce again, but this time I changed the callback to multiply() and also added an additional parameters as the initial value.

Note that if the initial value is lacking, then the output would be 0. Because at the beginning of the array_reduce execution, it would do something like 0*…. So no matter what the value we have, the outcome would be zero… So put in the third param here as the initial value. Then that’s it. The output would be 480 if using the example above

Advertisements