Created
January 23, 2017 01:22
-
-
Save jsiesquen/5fd4f4ea6fbea4300dfa68c1da402378 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class for complete the numbers from an input range | |
* Restrictions: | |
* - Letters are invalids, number only please. | |
* - If add negative numbers these are remove and | |
* the result init from a positive number like 1. | |
* - If add the zero number the result is empty string. | |
* Execution using: | |
* - From Code Inside, instance from Class: | |
* $cr = new CompleteRange(); | |
* echo $cr->build('5,8,19,34'); | |
*/ | |
class CompleteRange | |
{ | |
var $output = array(); | |
function __construct() | |
{ | |
} | |
function positiveOnly($var) | |
{ | |
// Return positive integer only | |
return($var > 0); | |
} | |
/** | |
* Complete Range | |
*/ | |
function build($inputString = null) | |
{ | |
$input = explode(',', $inputString); | |
$input = array_filter($input, "CompleteRange::positiveOnly"); | |
if (count($input) > 0) | |
{ | |
$range = range( isset($input[0]) ? $input[0]:1, array_pop($input)); | |
$result = array_diff($range, $input); | |
$this->output = array_merge($input, $result); | |
sort($this->output); | |
} | |
return "Input String:\n" . $inputString . "\n\n" . | |
"Result:\n" . implode(",", $this->output); | |
} | |
} | |
$cr = new CompleteRange(); | |
echo $cr->build('-6,-4,5,8,'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment