Skip to content

Instantly share code, notes, and snippets.

@mledoze
Created June 27, 2012 14:10
Show Gist options
  • Save mledoze/3004285 to your computer and use it in GitHub Desktop.
Save mledoze/3004285 to your computer and use it in GitHub Desktop.
PHP implementaion for "Home On The Range" Code Golf's challenge
<?php
/*
* http://codegolf.com/home-on-the-range
*
* The Problem
* It's difficult to spot what's missing in a long list of numbers if they are just listed one after the other.
* You can make it easier by organising the numbers into ranges, and that's exactly what you're going to do here.
*
* Your program will receive a set of space-separated numbers on stdin, and it will be expected to print a set of
* ranges on stdout formatted according to the following rules :
* - Numbers which appear sequentially in the input should be grouped with the first number and last number in the
* sequence separated by a hyphen.
* - Numbers which appear in the input on their own should not be collapsed into a range.
* - Ranges and single numbers in your output should be separated by a comma and a space (", "), and the list of
* ranges should end with a full-stop (".")
*
* Examples
* "1 2 3" => "1-3."
* "1 2 3 5 7 8" => "1-3, 5, 7-8."
* "1 3 4 5 7" => "1, 3-5, 7."
* "7 8 9 15 16 17 20 35 68 69 70 71 72" => "7-9, 15-17, 20, 35, 68-72."
* "7 9 15 17 20 35 68 70 72" => "7, 9, 15, 17, 20, 35, 68, 70, 72."
*/
$numbers = explode(' ', rtrim(fgets(fopen("php://stdin", "r"))));
$result = '';
for ($i = 0, $len = count($numbers); $i < $len; $i++) {
$j = $i;
while (($i + 1 < $len) && (($numbers[$i + 1] - $numbers[$i]) == 1)) {
$i++;
}
$result .= $numbers[$j] . ($i > $j ? '-' . $numbers[$i] : '') . (($i < $len - 1) ? ', ' : '.');
}
echo $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment