mod geek
mod geek

Reputation: 310

How To Resolve Str_pad issue in php

I am trying to perform multiplication but i am unable to format with str_pad but i am unable to do in this format

for example if i am trying to multiply. 421 by 675

 I want to do exactly in this format

         4 2 1
      x  6 7 5
      __________
       2 1 0 5
     2 9 4 7 x
   2 5 2 6 x x
________________
   2 8 4 1 7 5

but there is a problem in padding i am unable to show these x in the str_pad it is not working properly when i am using this format. It is displaying like this

padd

this is the code

$multiplier = 421;
$multiplicand = 675;
$result = $multiplier * $multiplicand;
$pad_max = strlen($result);

$multiplicand_values = str_split($multiplicand);

echo str_pad($multiplier, $pad_max, " ", STR_PAD_LEFT) . PHP_EOL;
echo "<br/>";
echo str_pad("x" . $multiplicand, $pad_max, " ", STR_PAD_LEFT) . PHP_EOL;
echo "<br/>";
echo str_pad("-", $pad_max, "-", STR_PAD_LEFT) . PHP_EOL;
 echo "<br/>";

for($i = 0; null !== ($digit = array_pop($multiplicand_values)); ++$i)
{
    echo str_pad($multiplier * $digit * pow(1, $i), $pad_max, " ", STR_PAD_LEFT) . PHP_EOL;
    echo "<br/>";
}

 echo "<br/>";
echo str_pad("-", $pad_max, "-", STR_PAD_LEFT) . PHP_EOL;
echo "<br/>";
echo str_pad($result, $pad_max, " ", STR_PAD_LEFT) . PHP_EOL;

Upvotes: 1

Views: 83

Answers (1)

Thamilhan
Thamilhan

Reputation: 13313

You can simply try with sprintf:

$multiplier = 421;
$multiplicand = 675;
$result = $multiplier * $multiplicand;
$pad_max = strlen($result);

$multiplicand_values = str_split($multiplicand);

echo sprintf("%${pad_max}s", $multiplier)."<br/>";
echo sprintf("%${pad_max}s", "x".$multiplicand)."<br/>";
echo str_repeat("_", $pad_max)."<br/>";

for($i = 0; null !== ($digit = array_pop($multiplicand_values)); ++$i)
{
    $value = $multiplier * $digit * pow(1, $i);
    $xValue = str_repeat("x", $i);
    echo sprintf("%${pad_max}s", $value.$xValue)."<br/>";
}

echo str_repeat("_", $pad_max)."<br/>";
echo $result;

Result:

   421
  x675
______
  2105
 2947x
2526xx
______
284175

Demo


For getting this output:

      4 2 1
    x 6 7 5
___________
    2 1 0 5
  2 9 4 7 x
2 5 2 6 x x
___________
2 8 4 1 7 5

You need to split the words. I used wordwrap:

$multiplier = 421;
$multiplicand = 675;
$result = $multiplier * $multiplicand;
$pad_max = strlen(word_Wrap($result));

$multiplicand_values = str_split($multiplicand);

echo sprintf("%${pad_max}s", word_Wrap($multiplier))."<br/>";
echo sprintf("%${pad_max}s", word_Wrap("x".$multiplicand))."<br/>";
echo str_repeat("_", $pad_max)."<br/>";

for($i = 0; null !== ($digit = array_pop($multiplicand_values)); ++$i)
{
    $value = $multiplier * $digit * pow(1, $i);
    $xValue = str_repeat("x", $i);
    echo sprintf("%${pad_max}s", word_Wrap($value.$xValue))."<br/>";
}

echo str_repeat("_", $pad_max)."<br/>";
echo word_Wrap($result);

function word_Wrap($value) {
    return wordwrap($value, 1, " ", true);
}

Upvotes: 1

Related Questions