Code Golf:数字范围
挑战
通过用范围替换连续的运行来压缩一长串数字。
示例
输入
1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15
输入保证按升序排列,并且不会包含重复项。
输出
1 - 4, 7, 8, 10, 12 - 15
请注意,两个数字的范围应保持原样。 (7, 8
;不是 7 - 8
)
规则
您可以从命令行或标准接受整数排序列表(或等效数据类型)作为方法参数in.(选择导致代码较短的选项)
您可以通过打印字符串或返回单个字符串或字符串集来输出字符串列表。
参考实现
(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);
}
}
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
The input is guaranteed to be in ascending order and will not contain duplicates.
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 sorted 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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
Python,98 个字符
Python - 86 个字符
这个末尾不包含额外的“,”
Python, 98 characters
Python - 86 characters
This one doesn't include an extra ',' at the end
Python,83 个字符
演示:
Python, 83 characters
Demo:
红宝石,165 个字符
Ruby, 165 characters
C++,166 个字符
难道你们不都喜欢滥用
?:
运算符吗? ;)更可读的版本:
C++, 166 characters
Don't you all just love abusing the
?:
operator? ;)More readable version:
Common Lisp,442/206 个字符
“d”函数将输入列表重写为规范形式。为了好玩,我完全递归地做到了这一点。 “p”函数将输出格式化为参考实现的等效项。
Common Lisp, 442/206 chars
The "d" function rewrites the input list into a canonical form. For fun I did this entirely recursively. The "p" function formats the output to the equivalent of the reference implementation.
F#,188 个字符
更具可读性:
F#, 188 chars
More readable:
Ruby:123 个字符
更具可读性
和执行性
Ruby : 123 characters
More Readable
And execute like
PHP 95 个字符
(实际上它是继 python 之后的第二语言)
给定
$a=array(numbers);
算法:
PHP 95 chars
(actually it's the second language after python)
Given
$a=array(numbers);
Algos: