3
Edsol
6y

DailyCodingProblem: #1

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

this is my quickly solution in php:
$input_array = [1, 2, 3, 4, 5];

echo('INPUT ARRAY:');
print_r($input_array);
echo("<br/>");

foreach($input_array as $key => $value){
$works_input_array = $input_array;
unset($works_input_array[$key]);

$result[] = array_product($works_input_array);
}
echo('OUTPUT ARRAY:');
print_r($result);

outpout:

INPUT ARRAY:Array ( [0] => 3 [1] => 2 [2] => 1 )
OUTPUT ARRAY:Array ( [0] => 2 [1] => 3 [2] => 6 )

Comments
  • 2
    JavaScript:

    const total = input_array.reduce((acc, num) => acc * num, 1),
    output_array = input_array.map(x => total / x);

    (more or less)
  • 0
    Mathematica

    f[a_] := Table[Multiply@@Drop[a, i],{i,1,Length[a]}]
  • 0
    @cannonau the Product x / x_i is very nice!
  • 1
    godammit 5min edit limit
    f[a_] := Multiply@@a*a^-1
  • 0
    @groenkek thanks, I later realised you'd have to account for one of the items being 0 though (maybe you did, I don't read mathematica)
Add Comment