计算超集


18

您的任务很简单:

给定整数集列表,找到集合并集。换句话说,找到包含原始集列表中的所有元素(但没有其他元素)的整数集的最短列表。例如:

[1,5] and [3,9] becomes [1,9] as it contains all of the elements in both [1,5] and [3,9]
[1,3] and [5,9] stays as [1,3] and [5,9], because you don't want to include 4

集使用范围表示法表示:[1,4]表示整数1,2,3,4。集也可以是无界的:[3,]表示所有整数>= 3,并且[,-1]表示所有整数<= -1。确保范围的第一个元素不大于第二个。

您可以选择采用字符串符号表示的集合,也可以使用2元素元组,并使用常量非整数作为“无限”值。您可以使用两个不同的常量来表示无限的上限和无限的下限。例如,在Javascript中,只要您在所有测试用例中都使用一致,就可以使用它[3,{}]来标记所有整数。>= 3{}

测试用例:

[1,3]                     => [1,3]
[1,]                      => [1,]
[,9]                      => [,9]
[,]                       => [,]
[1,3],[4,9]               => [1,9]
[1,5],[8,9]               => [1,5],[8,9]
[1,5],[1,5]               => [1,5]
[1,5],[3,7]               => [1,7]
[-10,7],[1,5]             => [-10,7]
[1,1],[2,2],[3,3]         => [1,3]
[3,7],[1,5]               => [1,7]
[1,4],[8,]                => [1,4],[8,]
[1,4],[-1,]               => [-1,]
[1,4],[,5]                => [,5]
[1,4],[,-10]              => [1,4],[,-10]
[1,4],[,]                 => [,]
[1,4],[3,7],[8,9],[11,20] => [1,9],[11,20]

这是,因此请尽可能短地回答!



1
我可以Infinity改用{}吗?
路易斯·费利佩·德·耶稣·穆尼奥斯

我们可以将输入作为浮点值,例如,[1.0, 3.0]而不是[1, 3]吗?
AdmBorkBork

只要您将它们视为整数,就可以。换句话说[1.0, 3.0], [4.0, 5.0],仍然应该成为[1.0, 5.0]
Nathan Merrill

如果您的语言不能接受Infinity-Infinity作为输入,是否可以接受-999999999999(或什至更大或更小)?
凯文·克鲁伊森

Answers:


7

R + intervals90 87 81字节

function(...)t(reduce(Intervals(rbind(...),type="Z")))+c(1,-1)
library(intervals)

在线尝试!

输入是间隔列表。-Inf并且Inf是R内置的负/正无穷大。输出是间隔列的矩阵。

通常不喜欢使用非标准库,但这很有趣。TIO尚未intervals安装。您可以在自己的安装中或在https://rdrr.io/snippets/上尝试

intervals程序包支持实数和整数(type = "Z")间隔,并且该reduce函数是挑战所需内容的内置函数,但是输出似乎默认为打开间隔,因此需要此函数才能获得所需的结果。close_intervals +c(1,-1)

旧版本在列表列表中有示例,可能会很方便,因此我在此处留下了链接。


我想你可以节省几个字节:function(...)close_intervals(reduce(Intervals(rbind(...),type="Z")))。甚至更好的是,您可以与op一起检查是否允许矩阵作为输入。
JayCe

1
昨晚我真的躺在床上醒着,想着“一定有更好的方法可以从输入向量中制作矩阵”。我认为挑战是最好保持输入不变。但它是有乐趣reduce,并Reduce在那里。
ngm

我爱“双重减少”的事情!只是没有足够的golfy;)有关修改开区间这样什么:f=function(...)t(reduce(Intervals(rbind(...),type="Z")))+c(1,-1)
JayCe

6

JavaScript(ES6),103个字节

感谢@Shaggy 保存了1个字节感谢@KevinCruijssen
保存了1个字节

预计+/-Infinity无限价值。

a=>(a.sort(([p],[P])=>p-P).map(m=M=([p,q])=>p<M+2?M=q>M?q:M:(b.push([m,M]),m=p,M=q),b=[]),b[0]=[m,M],b)

在线尝试!

怎么样?

我们首先按照区间的下限(从最低到最高)对区间进行排序。上限被忽略。

然后,我们在排序的时间间隔[pn,qn]进行迭代,同时跟踪当前的上下限mM,分别将其初始化为p1q1

对于每个间隔[pn,qn]

  • 如果pnM+1:这个间隔可以与前面的合并。但是我们可能有一个新的上限,因此我们将M更新为最高中号qñ
  • [中号]中号pñqñ

[中号]

已评论

a => (                  // a[] = input array
  a.sort(([p], [P]) =>  // sort the intervals by their lower bound; we do not care about
    p - P)              // the upper bounds for now
  .map(m = M =          // initialize m and M to non-numeric values
    ([p, q]) =>         // for each interval [p, q] in a[]:
    p < M + 2 ?         //   if M is a number and p is less than or equal to M + 1:
      M = q > M ? q : M //     update the maximum M to max(M, q)
    : (                 //   else (we've found a gap, or this is the 1st iteration):
      b.push([m, M]),   //     push the interval [m, M] in b[]
      m = p,            //     update the minimum m to p
      M = q             //     update the maximum M to q
    ),                  //
    b = []              //   start with b[] = empty array
  ),                    // end of map()
  b[0] = [m, M], b      // overwrite the 1st entry of b[] with the last interval [m, M]
)                       // and return the final result

p<=M+1可以p<M+2吗?
凯文·克鲁伊森

@KevinCruijssen我完全错过了那个……谢谢!
Arnauld

4

Python 2中118 113 112 111 106 105个 104 101字节

x=input()
x.sort();a=[];b,c=x[0]
for l,r in x:
 if l>c+1:a+=(b,c),;b,c=l,r
 c=max(c,r)
print[(b,c)]+a

多亏了Xcoder先生,节省了一个字节,感谢Jonathan Frech节省了一个字节,感谢Dead Possum节省了三个字节。
在线尝试!


(b,c),保存一个字节。
Xcoder先生18年

thought,以为我已经尝试过了。

并不g意味着您的功能f不可重用,因此无效吗?
尼尔

@Neil可能,但这只是先前尝试的一个保留。

1
您也可以为另一个字节执行return变为print
乔纳森·弗雷希

2

红宝石89 76字节

->a{[*a.sort.reduce{|s,y|s+=y;y[0]-s[-3]<2&&s[-3,3]=s.max;s}.each_slice(2)]}

在线尝试!

对数组进行排序,然后通过将所有范围附加到第一个范围进行展平:如果范围与前一个范围重叠,则从后三个范围中丢弃2个元素(仅保留最大值)。

最后展开所有内容。


1

帕斯卡(FPC) 367个 362 357字节

uses math;type r=record a,b:real end;procedure d(a:array of r);var i,j:word;t:r;begin for i:=0to length(a)-1do for j:=0to i do if a[i].a<a[j].a then begin t:=a[i];a[i]:=a[j];a[j]:=t;end;j:=0;for i:=1to length(a)-1do if a[j].b>=a[i].a-1then begin a[j].a:=min(a[i].a,a[j].a);a[j].b:=max(a[i].b,a[j].b)end else j:=j+1;for i:=0to j do writeln(a[i].a,a[i].b)end;

在线尝试!

该过程采用由2个范围边界组成的动态记录数组,对数组进行适当修改,然后将其写入标准输出,每行一个范围。(很抱歉,这个扭曲的句子。)用于无界1/0向上和-1/0无界向下。

可读版本

仅返回具有正确数目的元素的数组会很好,但是传递给函数/过程的动态数组不再是动态数组...首先,我找到了这个,然后有一个很棒的,令人费解的解释

这是我可以找到的用于缩短代码的最佳数据结构。如果您有更好的选择,请随时提出建议。


1

Wolfram语言(Mathematica),57个字节

List@@(#-{0,1}&/@IntervalUnion@@(Interval[#+{0,1}]&/@#))&

在线尝试!

将输入作为{a,b}代表时间间隔的列表的列表[a,b],其中abe可以-Infinitybbe可以Infinity

使用内置的IntervalUnion,但我们当然必须先将间隔按摩成形状。为了假装间隔是整数,我们将1加到上限(确保[1,3]and的并集[4,9][1,9])。最后,我们撤消该操作,然后将结果返回到列表列表。

还有一种完全不同的方法,它的时钟为73个字节

NumericalSort@#//.{x___,{a_,b_},{c_,d_},y___}/;b+1>=c:>{x,{a,b~Max~d},y}&

在这里,在对间隔进行排序之后,只要将两个连续的间隔合并为一个间隔,便用它们的并集替换它们,然后重复进行直到没有剩下要进行的此类操作为止。


1

05AB1E(旧版)88 79 78 字节

g≠i˜AKïDW<UZ>VIøεAXY‚Nè:}ïø{©˜¦2ôíÆ1›.œʒíεćsO_*}P}н€g®£εø©θàDYQiA}V®нßDXQiA}Y‚

输入无穷大作为小写字母('abcdefghijklmnopqrstuvwxyz')。

在线尝试验证所有测试用例

重要说明:如果有一个实际的Infinity-Infinity,则应该是43 42个字节。所以,略超过50%, 30%左右是作为变通的缺乏Infinity..

{©Dg≠i˜¦2ôíÆ1›.œʒíεćsO_*}P}н€g®£εø©θàV®нßY‚

在线试用(与Infinity替换为9999999999-Infinity替换成-9999999999)。

绝对可以打高尔夫球。最后,结果发现非常非常丑陋的解决方法。但是现在我很高兴它正在工作。

说明:

Dgi          # If the length of the implicit input is NOT 1:
              #   i.e. [[1,3]] → length 1 → 0 (falsey)
              #   i.e. [[1,4],["a..z",-5],[3,7],[38,40],[8,9],[11,20],[25,"a..z"],[15,23]]
              #    → length 8 → 1 (truthy)
    ˜         #  Take the input implicit again, and flatten it
              #   i.e. [[1,4],["a..z",-5],[3,7],[38,40],[8,9],[11,20],[25,"a..z"],[15,23]]
              #    → [1,4,"a..z",-5,3,7,38,40,8,9,11,20,25,"a..z",15,23]
     AK       #  Remove the alphabet
              #   i.e. [1,4,"a..z",-5,3,7,38,40,8,9,11,20,25,"a..z",15,23]
              #    → ['1','4','-5','3','7','38','40','8','9','11','20','25','15','23']
       ï      #  Cast everything to an integer, because `K` turns them into strings..
              #   i.e. ['1','4','-5','3','7','38','40','8','9','11','20','25','15','23']
              #    → [1,4,-5,3,7,38,40,8,9,11,20,25,15,23]
        D     #  Duplicate it
         W<   #  Determine the min - 1
              #   i.e. [1,4,-5,3,7,38,40,8,9,11,20,25,15,23] → -5
           U  #  Pop and store it in variable `X`
         Z>   #  Determine the max + 1
              #   i.e. [1,4,-5,3,7,38,40,8,9,11,20,25,15,23] → 40
           V  #  Pop and store it in variable `Y`
Iø            #  Take the input again, and transpose/zip it (swapping rows and columns)
              #   i.e. [[1,4],["a..z",-5],[3,7],[38,40],[8,9],[11,20],[25,"a..z"],[15,23]]
              #    → [[1,'a..z',3,38,8,11,25,15],[4,-5,7,40,9,20,'a..z',23]]
  ε       }   #  Map both to:
   A          #   Push the lowercase alphabet
    XY       #   Push variables `X` and `Y`, and pair them into a list
       Nè     #   Index into this list, based on the index of the mapping
         :    #   Replace every alphabet with this min-1 or max+1
              #   i.e. [[1,'a..z',3,38,8,11,25,15],[4,-5,7,40,9,20,'a..z',23]]
              #    → [['1','-6','3','38','8','11','25','15'],['4','-5','7','40','9','20','41','23']]
ï             #  Cast everything to integers again, because `:` turns them into strings..
              #   i.e. [['1','-6','3','38','8','11','25','15'],['4','-5','7','40','9','20','41','23']]
              #    → [[1,-6,3,38,8,11,25,15],[4,-5,7,40,9,20,41,23]]
 ø            #  Now zip/transpose back again
              #   i.e. [[1,-6,3,38,8,11,25,15],[4,-5,7,40,9,20,41,23]]
              #    → [[1,4],[-6,-5],[3,7],[38,40],[8,9],[11,20],[25,41],[15,23]]
  {           #  Sort the pairs based on their lower range (the first number)
              #   i.e. [[1,4],[-6,-5],[3,7],[38,40],[8,9],[11,20],[25,41],[15,23]]
              #    → [[-6,-5],[1,4],[3,7],[8,9],[11,20],[15,23],[25,41],[38,40]]
   ©          #  Store it in the register (without popping)
˜             #  Flatten the list
              #   i.e. [[-6,-5],[1,4],[3,7],[8,9],[11,20],[15,23],[25,41],[38,40]]
              #    → [-6,-5,1,4,3,7,8,9,11,20,15,23,25,41,38,40]
 ¦            #  And remove the first item
              #   i.e. [-6,-5,1,4,3,7,8,9,11,20,15,23,25,41,38,40]
              #    → [-5,1,4,3,7,8,9,11,20,15,23,25,41,38,40]
  2ô          #  Then pair every two elements together
              #   i.e. [-5,1,4,3,7,8,9,11,20,15,23,25,41,38,40]
              #    → [[-5,1],[4,3],[7,8],[9,11],[20,15],[23,25],[41,38],[40]]
    í         #  Reverse each pair
              #   i.e. [[-5,1],[4,3],[7,8],[9,11],[20,15],[23,25],[41,38],[40]]
              #    → [[1,-5],[3,4],[8,7],[11,9],[15,20],[25,23],[38,41],[40]]
     Æ        #  Take the difference of each pair (by subtracting)
              #   i.e. [[1,-5],[3,4],[8,7],[11,9],[15,20],[25,23],[38,41],[40]]
              #    → [6,-1,1,2,-5,2,-3,40]
      1      #  Determine for each if they're larger than 1
              #   i.e. [6,-1,1,2,-5,2,-3,40] → [1,0,0,1,0,1,0,1]
            #  Create every possible partition of these values
              #   i.e. [1,0,0,1,0,1,0,1] → [[[1],[0],[0],[1],[0],[1],[0],[1]],
              #                             [[1],[0],[0],[1],[0],[1],[0,1]],
              #                             ...,
              #                             [[1,0,0,1,0,1,0],[1]],
              #                             [[1,0,0,1,0,1,0,1]]]
  ʒ         } #  Filter the partitions by:
   í          #   Reverse each inner partition
              #    i.e. [[1],[0,0,1],[0,1],[0,1]] → [[1],[1,0,0],[1,0],[1,0]]
    ε     }   #   Map each partition to:
     ć        #    Head extracted
              #     i.e. [1,0,0] → [0,0] and 1
              #     i.e. [1] → [] and 1
              #     i.e. [1,0,1] → [1,0] and 1
      s       #    Swap so the rest of the list is at the top of the stack again
       O      #    Take its sum
              #     i.e. [0,0] → 0
              #     i.e. [] → 0
              #     i.e. [1,0] → 1
        _     #    And check if it's exactly 0
              #     i.e. 0 → 1 (truthy)
              #     i.e. 1 → 0 (falsey)
         *    #    And multiply it with the extracted head
              #    (is only 1 when the partition has a single trailing 1 and everything else a 0)
              #     i.e. 1 and 1 → 1 (truthy)
              #     i.e. 1 and 0 → 0 (falsey)
           P  #   And check if all mapped partitions are 1
н             #  Take the head (there should only be one valid partition left)
              #   i.e. [[[1],[0,0,1],[0,1],[0,1]]] → [[1],[0,0,1],[0,1],[0,1]]
 g           #  Take the length of each inner list
              #   i.e. [[1],[0,0,1],[0,1],[0,1]] → [1,3,2,2]
   ®          #  Push the sorted pairs we've saved in the register earlier
    £         #  Split the pairs into sizes equal to the partition-lengths
              #   i.e. [1,3,2,2] and [[-6,-5],[1,4],[3,7],[8,9],[11,20],[15,23],[25,41],[38,40]]
              #    → [[[-6,-5]],[[1,4],[3,7],[8,9]],[[11,20],[15,23]],[[25,41],[38,40]]]
ε             #  Map each list of pairs to:
 ø            #   Zip/transpose (swapping rows and columns)
              #    i.e. [[1,4],[3,7],[8,9]] → [[1,3,8],[4,7,9]]
              #    i.e. [[25,41],[38,40]] → [[25,38],[41,40]]
  ©           #   Store it in the register
   θ          #   Take the last list (the ending ranges)
              #    i.e. [[25,38],[41,40]] → [41,40]
    à         #   And determine the max
              #    i.e. [41,40] → 41
     DYQi }   #   If this max is equal to variable `Y`
              #     i.e. 41 (`Y` = 41) → 1 (truthy)
         A    #    Replace it back to the lowercase alphabet
           V  #   Store this max in variable `Y`
  ®           #   Take the zipped list from the register again
   н          #   This time take the first list (the starting ranges)
              #    i.e. [[25,38],[41,40]] → [25,38]
    ß         #   And determine the min
              #    i.e. [25,38] → 25
     DXQi }   #   If this min is equal to variable `X`
              #     i.e. 25 (`X` = -6) → 0 (falsey)
         A    #    Replace it back to the lowercase alphabet
           Y #   And pair it up with variable `Y` (the max) to complete the mapping
              #    i.e. 25 and 'a..z' → [25,'a..z']
              #  Implicitly close the mapping (and output the result)
              #   i.e. [[[-6,-5]],[[1,4],[3,7],[8,9]],[[11,20],[15,23]],[[25,41],[38,40]]]
              #    → [['a..z',-5],[1,9],[11,23],[25,'a..z']]
              # Implicit else (only one pair in the input):
              #  Output the (implicit) input as is
              #   i.e. [[1,3]]

1

C(clang)346342字节

编译器标志-DP=printf("(%d,%d)\n"-DB=a[i+1]-DA=a[i]

typedef struct{int a,b;}t;s(t**x,t**y){if((*x)->a>(*y)->a)return 1;else if((*x)->a<(*y)->a)return -1;}i;f(t**a){for(i=0;A;)i++;qsort(a,i,sizeof(t*),s);for(i=0;B;i++){if(B->a<=A->b+1){A->b=B->b;if(B->a<A->a)A->a=B->a;else B->a=A->a;}}for(i=0;A;i++){if(!B)break;if(A->a!=B->a)P,A->a,A->b);}P,A->a,A->b);}

在线尝试!


我认为您依靠i的是全球价值。
乔纳森·弗雷希

@JonathanFrech的意思是while(A)i++;应该在while循环中使用它之前进行for(i=0;A;)i++;显式设置i=0,而不是0在全局级别使用其默认值。现在不知道为什么,但是根据元规则是必需的。主要是因为方法应该是独立的/可重复使用的,而不必在两次方法调用之间(IIRC)重置全局值。
凯文·克鲁伊森

固定依赖全球i价值
Logern 18'Sep



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.