Skip to content

Instantly share code, notes, and snippets.

@vdubyna
Created February 28, 2017 10:27
Show Gist options
  • Save vdubyna/906263e2ff536a57e4dee341bbbf95af to your computer and use it in GitHub Desktop.
Save vdubyna/906263e2ff536a57e4dee341bbbf95af to your computer and use it in GitHub Desktop.
Multiply 2 numbers
function multiplyInColumn($a, $b) {
$bArr = array_reverse(str_split($b));
$aArr = array_reverse(str_split($a));
$result = array_map(function ($step, $bItem) use ($aArr) {
$rest = 0;
$result = array_fill(0, $step, 0);
foreach ($aArr as $key => $aItem) {
$r = ($bItem * $aItem) + $rest;
if ($r < 10) {
$result[] = $r;
$rest = 0;
} else {
if ($key === (count($aArr) - 1)) {
$result[] = $r;
$rest = 0;
} else {
$result[] = (int) substr($r, -1);
$rest = substr($r, 0, 1);
}
}
}
return array_reduce($result, function ($carry, $item) {
return $item . $carry;
});
}, array_keys($bArr), $bArr);
return array_sum($result);
}
echo multiplyInColumn(12345, 12) . PHP_EOL;
echo multiplyInColumn(11, 1) . PHP_EOL;
echo multiplyInColumn(10, 999) . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment