Skip to content

Instantly share code, notes, and snippets.

@mccarlosen
Created March 8, 2018 17:34
Show Gist options
  • Save mccarlosen/eac8219a1fd845efc1583c771e4af15b to your computer and use it in GitHub Desktop.
Save mccarlosen/eac8219a1fd845efc1583c771e4af15b to your computer and use it in GitHub Desktop.
<?php
function reduce ($_int, $counter = 0) {
echo 'number : ' . $_int . ' <br> ' . 'counter: ' . $counter . ' <br> ----------------- <br>';
$intArray = preg_split('//', (string)$_int, -1, PREG_SPLIT_NO_EMPTY);
if(count($intArray) > 1){
return reduce ( array_sum($intArray), ($counter + $_int) );
} else {
return $counter + $_int;
}
}
print_r(reduce(9875));
<?php
class SumRecursive
{
public $num;
public function __construct($num)
{
$this->num = $num;
}
public function sum()
{
$results = [];
$sum = true;
$nums = $this->separe($this->num);
while ($sum) {
if (count($nums)) {
$result = array_sum($nums);
if (count($this->separe($result)) == 1) {
$sum = false;
}
$nums = $this->separe($result);
array_push($results, $result);
} else {
$sum = false;
}
}
return $this->draw($results);
}
public function draw($items)
{
if (count($items)) {
echo 'Resultados:<br>';
echo '--------------------<br>';
echo $this->num.'<br>';
echo '--------------------<br>';
foreach ($items as $item) {
echo $item.'<br>';
echo '--------------------<br>';
}
} else {
return 'Nada que hacer';
}
}
private function separe($num)
{
try {
$nums = [];
if ((int)$num == false) {
throw new Exception('No es un número válido.');
}
$nums = str_split($num);
if (!count($nums)) {
return $num;
}
foreach ($nums as $k => $n) {
$nums[$k] = (int)$n;
}
return $nums;
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
$num = new SumRecursive(9875);
$num->sum();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment