Replace each element with product of every other element
EASY
Given an input string with numbers separated by a single space.
Replace each element of the string with product of every other element in the string.
For example, line "1 2 3"
New value instead "1" is "2 * 3 = 6". For "2" is "1 * 3 = 3". For "3" is "1 * 2 = 2"
Solution
<?php
$line = trim(fgets(STDIN));
$nums = explode(' ', $line);
$product = null;
$productWithoutZero = null;
$zerosCount = 0;
foreach ($nums as $i => $num) {
if ($product === null) {
$product = $num;
} else {
$product *= $num;
}
if ($num == 0) {
$zerosCount++;
continue;
}
if ($productWithoutZero === null) {
$productWithoutZero = $num;
} else {
$productWithoutZero *= $num;
}
}
if ($zerosCount > 1) {
$productWithoutZero = 0;
}
foreach ($nums as $i => $num) {
if ($num == 0) {
echo $productWithoutZero . ' ';
continue;
}
echo $product / $num . ' ';
}
Tests
Test #1 |
Loading...
|
Test #2 |
Loading...
|
Test #3 |
Loading...
|
Test #4 |
Loading...
|
Test #5 |
Loading...
|
Test #6 |
Loading...
|