Code Golf: Numeric Ranges
Posted
by
SLaks
on Stack Overflow
See other posts from Stack Overflow
or by SLaks
Published on 2011-01-11T15:50:27Z
Indexed on
2011/01/11
15:53 UTC
Read the original article
Hit count: 214
language-agnostic
|code-golf
Mods: Can you please make this Community Wiki?
Challenge
Compactify a long list of numbers by replacing consecutive runs with ranges.
Example
Input
1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15
Output:
1 - 4, 7, 8, 10, 12 - 15
Note that ranges of two numbers should be left as is. (7, 8
; not 7 - 8
)
Rules
You can accept a list of integers (or equivalent datatype) as a method parameter, from the commandline, or from standard in. (pick whichever option results in shorter code)
You can output a list of strings by printing them, or by returning either a single string or set of strings.
Reference Implementation
(C#)
IEnumerable<string> Sample(IList<int> input) {
for (int i = 0; i < input.Count; ) {
var start = input[i];
int size = 1;
while (++i < input.Count && input[i] == start + size)
size++;
if (size == 1)
yield return start.ToString();
else if (size == 2) {
yield return start.ToString();
yield return (start + 1).ToString();
} else if (size > 2)
yield return start + " - " + (start + size - 1);
}
}
© Stack Overflow or respective owner