Code Golf:数字范围

发布于 2024-10-11 14:36:58 字数 999 浏览 3 评论 0原文

挑战

通过用范围替换连续的运行来压缩一长串数字。

示例

输入

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

梦幻的心爱 2024-10-18 14:36:58

Python,98 个字符

def f(a):
 for x in a:
  if x-1not in a or x+1not in a:print x,"-"if x+1in a and x+2in a else",",

Python - 86 个字符

这个末尾不包含额外的“,”

f=lambda a:''.join(`x`+",-"[(x+1in a)&x+2in a]for x in a if(x-1in a)&(x+1in a)^1)[:-1]

Python, 98 characters

def f(a):
 for x in a:
  if x-1not in a or x+1not in a:print x,"-"if x+1in a and x+2in a else",",

Python - 86 characters

This one doesn't include an extra ',' at the end

f=lambda a:''.join(`x`+",-"[(x+1in a)&x+2in a]for x in a if(x-1in a)&(x+1in a)^1)[:-1]
灰色世界里的红玫瑰 2024-10-18 14:36:58

Python,83 个字符

def f(l,a=2):
 for x in l:
  b,a=a,(x+1in l)*(x-1in l)
  if a<1:print',- '[b],`x`,

演示:

>>> l=[1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15]
>>> f(l)
  1 - 4 , 7 , 8 , 10 , 12 - 15

Python, 83 characters

def f(l,a=2):
 for x in l:
  b,a=a,(x+1in l)*(x-1in l)
  if a<1:print',- '[b],`x`,

Demo:

>>> l=[1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15]
>>> f(l)
  1 - 4 , 7 , 8 , 10 , 12 - 15
谈情不如逗狗 2024-10-18 14:36:58

红宝石,165 个字符

a=[]
def o(a)print "#{@s}#{a[0]}#{"#{a.size<3?',':' -'} #{a[-1]}"if a.size>1}";@s=', 'end
ARGV[0].split(', ').each{|n|if a[0]&&a[-1].succ!=n;o(a);a=[]end;a<<n;};o(a)

Ruby, 165 characters

a=[]
def o(a)print "#{@s}#{a[0]}#{"#{a.size<3?',':' -'} #{a[-1]}"if a.size>1}";@s=', 'end
ARGV[0].split(', ').each{|n|if a[0]&&a[-1].succ!=n;o(a);a=[]end;a<<n;};o(a)
孤芳又自赏 2024-10-18 14:36:58

C++,166 个字符

#define o std::cout
void f(std::vector<int> v){for(int i=0,b=0,z=v.size();i<z;)i==z-1||v[i+1]>v[i]+1?b?o<<", ":o,(i-b?o<<v[b]<<(i-b>1?" - ":", "):o)<<v[i],b=++i:++i;}

难道你们不都喜欢滥用 ?: 运算符吗? ;)

更可读的版本:

#define o std::cout
void f(std::vector<int> v){
    for(int i=0,b=0,z=v.size();i<z;)
        i==z-1||v[i+1]>v[i]+1 ?
            b?o<<", ":o,
            (i-b?o<<v[b]<<(i-b>1?" - ":", "):o)<<v[i],
            b=++i
        :++i;
}

C++, 166 characters

#define o std::cout
void f(std::vector<int> v){for(int i=0,b=0,z=v.size();i<z;)i==z-1||v[i+1]>v[i]+1?b?o<<", ":o,(i-b?o<<v[b]<<(i-b>1?" - ":", "):o)<<v[i],b=++i:++i;}

Don't you all just love abusing the ?: operator? ;)

More readable version:

#define o std::cout
void f(std::vector<int> v){
    for(int i=0,b=0,z=v.size();i<z;)
        i==z-1||v[i+1]>v[i]+1 ?
            b?o<<", ":o,
            (i-b?o<<v[b]<<(i-b>1?" - ":", "):o)<<v[i],
            b=++i
        :++i;
}
月光色 2024-10-18 14:36:58

Common Lisp,442/206 个字符

(defun d (l)
  (if l
      (let ((f (car l))
        (r (d (cdr l))))
      (if r
          (if (= (+ f 1) (caar r))
          (push `(,f ,(cadar r)) (cdr r))
          (push `(,f ,f) r))
          `((,f ,f))
          ))
      nil))

(defun p (l)
  (mapc #'(lambda (x)
          (if (= (car x) (cadr x))
          (format t "~a " (car x))
          (if (= (+ 1 (car x)) (cadr x))
              (format t "~a ~a " (car x) (cadr x))
              (format t "~a-~a " (car x) (cadr x)))))
      (d l)))

“d”函数将输入列表重写为规范形式。为了好玩,我完全递归地做到了这一点。 “p”函数将输出格式化为参考实现的等效项。

Common Lisp, 442/206 chars

(defun d (l)
  (if l
      (let ((f (car l))
        (r (d (cdr l))))
      (if r
          (if (= (+ f 1) (caar r))
          (push `(,f ,(cadar r)) (cdr r))
          (push `(,f ,f) r))
          `((,f ,f))
          ))
      nil))

(defun p (l)
  (mapc #'(lambda (x)
          (if (= (car x) (cadr x))
          (format t "~a " (car x))
          (if (= (+ 1 (car x)) (cadr x))
              (format t "~a ~a " (car x) (cadr x))
              (format t "~a-~a " (car x) (cadr x)))))
      (d l)))

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.

飘逸的'云 2024-10-18 14:36:58

F#,188 个字符

let r(x::s)=
 let f=printf
 let p x=function|1->f"%A "x|2->f"%A %A "x (x+1)|n->f"%A-%A "x (x+n-1)
 let rec l x n=function|y::s when y=x+n->l x (n+1)s|y::s->p x n;l y 1 s|[]->p x n
 l x 1 s

更具可读性:

let range (x::xs) =
  let f = printf
  let print x = function
    | 1 -> f "%A " x
    | 2 -> f "%A %A " x (x+1)
    | n -> f "%A-%A " x (x+n-1)
  let rec loop x n = function
    | y::ys when y=x+n ->
        loop x (n+1) ys
    | y::ys ->
        print x n
        loop y 1 ys
    | [] ->
        print x n
  loop x 1 xs

F#, 188 chars

let r(x::s)=
 let f=printf
 let p x=function|1->f"%A "x|2->f"%A %A "x (x+1)|n->f"%A-%A "x (x+n-1)
 let rec l x n=function|y::s when y=x+n->l x (n+1)s|y::s->p x n;l y 1 s|[]->p x n
 l x 1 s

More readable:

let range (x::xs) =
  let f = printf
  let print x = function
    | 1 -> f "%A " x
    | 2 -> f "%A %A " x (x+1)
    | n -> f "%A-%A " x (x+n-1)
  let rec loop x n = function
    | y::ys when y=x+n ->
        loop x (n+1) ys
    | y::ys ->
        print x n
        loop y 1 ys
    | [] ->
        print x n
  loop x 1 xs
寄居人 2024-10-18 14:36:58

Ruby:123 个字符

def y(n) t=[];r=[];n.each_with_index do |x,i| t<<x;if(x.succ!=n[i+1]);r=((t.size>2)?r<<t[0]<<-t[-1]:r+t);t=[];end;end;r;end

更具可读性

def y(n) 
t=[];r=[];
n.each_with_index do |x,i|
 t << x
 if (x.succ != n[i+1])
    r = ((t.size > 2) ? r << t[0] << -t[-1] : r+t)  
    t=[]
 end
 end
 r
end

和执行性

 > n=[1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15]
 > y n
 => [1, -4, 7, 8, 10, 12, -15]

Ruby : 123 characters

def y(n) t=[];r=[];n.each_with_index do |x,i| t<<x;if(x.succ!=n[i+1]);r=((t.size>2)?r<<t[0]<<-t[-1]:r+t);t=[];end;end;r;end

More Readable

def y(n) 
t=[];r=[];
n.each_with_index do |x,i|
 t << x
 if (x.succ != n[i+1])
    r = ((t.size > 2) ? r << t[0] << -t[-1] : r+t)  
    t=[]
 end
 end
 r
end

And execute like

 > n=[1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15]
 > y n
 => [1, -4, 7, 8, 10, 12, -15]
妄断弥空 2024-10-18 14:36:58

PHP 95 个字符

(实际上它是继 python 之后的第二语言

给定 $a=array(numbers);

算法:

for($i=0;$i<count($a);$i++){$c=$i;while($a[$i+2]==$a[$i]+2)$i++;echo $a[$c],$i-$c>1?'-':',';}

PHP 95 chars

(actually it's the second language after python)

Given $a=array(numbers);

Algos:

for($i=0;$i<count($a);$i++){$c=$i;while($a[$i+2]==$a[$i]+2)$i++;echo $a[$c],$i-$c>1?'-':',';}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文