Skip to content

Instantly share code, notes, and snippets.

@jsiesquen
Created January 23, 2017 01:22
Show Gist options
  • Save jsiesquen/5fd4f4ea6fbea4300dfa68c1da402378 to your computer and use it in GitHub Desktop.
Save jsiesquen/5fd4f4ea6fbea4300dfa68c1da402378 to your computer and use it in GitHub Desktop.
<?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