最长相等子序列


18

定义

  • 子序列可能不是连续的,例如[1, 1, 1]是的子序列[1, 2, 1, 2, 1]
  • 相等的子序列是每个元素都相等的子序列。
  • 最长等于序列可能不是唯一的,例如,[1, 1][2, 2]是两个最长等于子序列[2, 1, 1, 2]

输入值

一个非整数的正整数列表,格式如下:

  • 作为您语言中正整数数组的本地实现
  • 作为以换行符分隔的整数的字符串(十进制)
  • 作为一串以换行符分隔的整数(一元)
  • 任何其他合理的格式

输出量

以下列格式之一按任何顺序排列的所有最长相等子序列:

  • 作为您语言中的2D嵌套数组(如果输入是数组)
  • 作为带有相等元素的连续数组
  • 任何其他合理格式

计分

尽管我们在寻找长的东西,但是使用的代码就字节数而言应尽可能短,因为这是

测试用例

输入:

[1, 2, 3]
[1, 2, 2, 1]
[1, 2, 3, 2, 1]
[1, 2, 1, 2, 3, 4, 1]

输出:

[[1], [2], [3]]
[[1, 1], [2, 2]]
[[1, 1], [2, 2]]
[[1, 1, 1]]

请注意,对于以上输出,任何订单均有效。

只要相等的元素是连续的,展平的数组也是有效的。


4
谈论“最频繁的元素” IMO会更简单:当顺序很重要时使用子序列,但是在这里,输入的每个排列都具有相同的一组允许的正确输出。
ShreevatsaR '17

@ShreevatsaR抱歉,我已经编辑了问题。
Leaky Nun

平面列表可用于输出吗?例如1 2 31 1 2 21 1 2 21 1 1
Conor O'Brien

@ ConorO'Brien说“是”将使此处的大部分答案无效……
Leaky Nun

@LeakyNun一样,它是可以接受的替代方法吗?
科纳·奥布莱恩

Answers:


8

果冻,5个字节

ĠLÐṀị

在线尝试!

怎么运行的

ĠLÐṀị  Main link. Argument: A (array)

Ġ      Group; partition the indices of A by their corresponding values.
 LÐṀ   Select all index arrays with maximal length.
    ị  Unindex; retrieve the items of A at the specified indices.

我以为Jelly没有
最快的

这是技术上的一个最大的快,但肯定的,它的作用。
丹尼斯

5

Brachylog,7个字节

⊇ᶠ=ˢlᵍh

在线尝试!

说明

⊇ᶠ=ˢlᵍh
⊇ᶠ        Find all subsequences
  =ˢ      Keeping only those for which all elements are equal
    lᵍ    Group by length
      h   Take the first group

的自然顺序首先生成最长的子序列,因此这些序列在第一组中结束。


1
噢,另一位速记员。
Leaky Nun

1
不知怎的,您和我一定在Brachylog聊天中多次想念对方。我使用它已有几个月了,很惊讶地发现除Fatalize之外的其他人也是如此。

5

Pyth,5个字节

S.M/Q

测试套件

说明:

这是隐含的S.M/QZQ.M是最大函数,因此.M/QZQ选择所有元素,其中的值/QZ计算输入中元素出现的次数为最大。S然后对列表进行排序,以使相同的元素连续。


3

bash,66个字节

sort|uniq -c|sort -rn|awk 'NR==1{a=$1}$1==a{for(i=a;i--;)print$2}'

这似乎应该更短一些,但是我不知道怎么做。

sort                  # sort the input
|uniq -c              # group runs of identical lines and prefix with count
|sort -rn             # sort by count, with largest at top
|awk '                # pipe to awk...
  NR==1{a=$1}         # on the first line, set the variable "a" to field 1
  $1==a{              # on any line, if first field is a (max count)...
    for(i=a;i--;)     # a times...
    print$2           # print the second field
  }
'

在线尝试!

感谢Leaky Nun提供3个字节!



考虑更新你的解释
漏嫩

3

Python 2中68个 63字节

lambda x:sorted(n for n in x if x.count(n)/max(map(x.count,x)))

在线尝试!


想要在Python 3中看到答案:p
Leaky Nun

1
移植这个很简单:只需替换print为即可return
丹尼斯,

哦,我以为Python 3没有map
Leaky Nun

3有点不同(如果有两个以上的参数,则返回一个生成器并截断更长的可迭代对象),但是它在那里。
丹尼斯

我以为Python内置了此功能
Beta Decay's

2

Mathematica,42 31 25字节

感谢@GregMartin提供5个字节,而@MartinEnder提供另一个字节!

MaximalBy[Length]@*Gather

说明

MaximalBy[Length]@*Gather  (*                       {1, 2, 3, 2, 1}       *)
                   Gather  (* Gather same numbers:  {{1, 1}, {2, 2}, {3}} *)
                 @*        (* Function composition                        *)
MaximalBy[Length]          (* Find longest:         {{1, 1}, {2, 2}}      *)

1
您可以使用保存5个字节Gather@#~MaximalBy~Length&
格雷格·马丁

2
@GregMartin然后MaximalBy[Length]@*Gather
Martin Ender

我添加了另一个可以接受的替代方法,它可以帮助您节省一些字节。
Leaky Nun

2

堆叠55 52 43字节

sorted rle toarr:[1#]map MAX@K[1#K=]YES rld

在线尝试!

通过对输入进行游程长度编码,按出现次数排序,保持出现次数最大的出现次数以及运行长度解码来工作。挑战可接受的通过平面清单的输出。


2

实际上,23个字节

;╗⌠;╜ck⌡M;♂NM╗⌠N╜=⌡░♂FS

在线尝试,或运行所有测试用例

感谢Leaky Nun指出对我而言确实应该显而易见的一字节改进

宽松输出格式中的-3字节

说明:

;╗⌠;╜ck⌡M;♂NM╗⌠N╜=⌡░♂FS
;╗                        save a copy of the input to register 0
  ⌠;╜ck⌡M                 for each value in the input list:
   ;                        make a copy on the stack
    ╜c                      count the occurrences in the input list (from register 0)
      k                     make a list: [value, count]
         ;♂N             make a copy, take last value of each list in the 2D list
            M╗           store the maximum count in register 0
              ⌠N╜=⌡░     filter the other copy of the list of [value, count] lists:
               N╜=         take items where the count equals the maximum count
                    ♂FS  take first items (values) and sort them

1

Python 2,138字节

lambda l:[[x[0]]*x[1] for x in next(__import__('itertools').groupby(__import__('collections').Counter(l).most_common(),lambda x:x[1]))[1]]

itertools从来都不是最短的时间:p
Leaky Nun'5

我添加了另一个可以接受的替代方法,它可以帮助您节省一些字节。
Leaky Nun

1

MATL,10字节

3#XMg1bX"&

在线尝试!

说明

类似于我的八度音阶答案。以输入[10, 20, 30, 20, 10]为例。

3#XM   % Three-output version of mode function. Gives the first mode, the
       % number of repetitions, and a cell array with all modes
       % STACK: 10, 2, {10; 20}
g      % Convert from cell array to matrix
       % STACK: 10, 2, [10; 20]
1      % Push 1
       % STACK: 10, 2, [10; 20], 1
b      % Bubble up in the stack
       % STACK: 10, [10; 20], 1, 2
X"     % Repeat those number of times vertically and horizontally
       % STACK: 10, [10, 10; 20, 20]
&      % Specify that implicit display will show only the top of the stack.
       % Since this is singleton cell array that contains a matrix, that 
       % matrix is directly displayed

我添加了另一个可以接受的替代方法,它可以帮助您节省一些字节。
Leaky Nun

@LeakyNun感谢您让我知道
Luis

这是我的责任。
Leaky Nun

1

八度,47字节

[~,b,c]=mode(input(0));disp([repmat(c,1,b){:}])

在线尝试!

说明

的第二个输出和第三个输出mode(作为获得[~,b,c]=mode(...))分别给出输入()中重复次数最多的元素的重复次数(b)和列单元格数组cinput(0))。c然后将单元格水平重复brepmat(c,1,b)),转换为逗号分隔的列表({:}),然后水平污染([...]),得到一个数字矩阵,将其显示(disp(...))。


我添加了另一个可以接受的替代方法,它可以帮助您节省一些字节。
Leaky Nun


1

CJam,22个字节

{$e`z~\__:e>f=.*\]ze~}

这是一个匿名块(函数),它从堆栈的顶部获取输入,并用输出重新填充。输出是一个平整的数组,其中相等的元素是连续的。

在线尝试!

说明

以输入[10 20 30 20 10 ]为例。

{      e# Begin block
       e#   STACK: [10 20 30 20 10]
  $    e#   Sort
       e#   STACK: [10 10 20 20 30]
  e`   e#   Run-length encoding
       e#   STACK: [[2 10] [2 20] [1 30]]
  z    e#   Zip
       e#   STACK: [[2 2 1] [10 20 30]]
  ~    e#   Dump array contents onto the stack
       e#   STACK: [2 2 1] [10 20 30]
  \    e#   Swap
       e#   STACK: [10 20 30] [2 2 1]
  __   e#   Duplicate twice
       e#   STACK: [10 20 30] [2 2 1] [2 2 1] [2 2 1]
  :e>  e#   Fold maximum over array. Gives the maximum of the array
       e#   STACK: [10 20 30] [2 2 1] [2 2 1] 2
  f=   e#   Map "is equal" with number (2) over the array ([2 2 1])
       e#   STACK: [10 20 30] [2 2 1] [1 1 0]
  .*   e#   Vectorized multiplication
       e#   STACK: [10 20 30] [2 2 0]
  \    e#   Swap
       e#   STACK: [2 2 0] [10 20 30]
  ]    e#   Pack into array
       e#   STACK: [[2 2 0] [10 20 30]]
  z    e#   Zip
       e#   STACK: [[2 10] [2 20] [0 30]]
  e~   e#   Run-length decoding
       e#   STACK: [10 10 20 20]
}      e# End block

1

Perl 5,58个字节

sub{sort grep$x{$_}>$m,grep{$/=$x{$_}++;$m=$/if$m<$/;1}@_}

0

APL(Dyalog),22字节

要求⎕ML←3在许多系统上是默认设置。

程序: s/⍨(⌈/=⊢)≢¨s←⊂⍨(⍋⊃¨⊂)⎕

 获取数字(评估)输入

() 隐式函数
 升序项的索引,
⊃¨ 它们从
 整个数组中 选取

⊂⍨ 通过减少增加来划分

s← 存储为s

≢¨ 总计

() 默认函数
⌈/ (最大值)
= 等于
 参数(计数)

s/⍨ 过滤器小号

功能: {s/⍨(⌈/=⊢)≢¨s←⊂⍨⍵[⍋⍵]}

{} 参数为的匿名函数

⍵[⍋⍵] 排序(带升序项索引的照明索引)

⊂⍨ 通过减少增加来划分

s← 存储为s

≢¨ 总计

() 默认函数
⌈/ (最大值)
= 等于
 参数(计数)

s/⍨ 过滤š在线试试吧!


我添加了另一个可以接受的替代方法,它可以帮助您节省一些字节。
Leaky Nun

0

PHP,69字节

<?print_r(preg_grep("#".max($r=array_count_values($_GET))."#",$r));

在线版本

输出格式

键=值,值=计数

Array
(
    [1] => 2
    [2] => 2
)

PHP,96字节

<?foreach($_GET as$v)$r[$m[]=count($l=preg_grep("#^{$v}$#",$_GET))][$v]=$l;print_r($r[max($m)]);

在线版本

输出格式

一维键=值

2D键=每个值在输入数组中的位置

Array
(
    [1] => Array
        (
            [0] => 1
            [4] => 1
        )

    [2] => Array
        (
            [1] => 2
            [3] => 2
        )

)

PHP,97字节

<?foreach($_GET as$v)$r[count($l=preg_grep("#^{$v}$#",$_GET))][$v]=$l;ksort($r);print_r(end($r));

我添加了另一个可以接受的替代方法,它可以帮助您节省一些字节。
Leaky Nun

0

JavaScript(ES6),84 83字节

返回排序的扁平化数组。

a=>a.sort().filter((_,i)=>b[i]==Math.min(...b),b=a.map(i=>a.filter(j=>i-j).length))

测试用例


我添加了另一个可以接受的替代方法,它可以帮助您节省一些字节。
Leaky Nun

@LeakyNun感谢您的通知。
Arnauld

0

CJam,24个字节

{$e`_$W=0=\{0=1$=},e~\;}

我想在05ab1e中这样做,但我放弃了:P

这是一个块。输入和输出是堆栈上的数组。

在线尝试!

说明:

{                      e# Stack:                | [1 2 3 2 1]
 $                     e# Sort:                 | [1 1 2 2 3]
  e`                   e# RLE encode:           | [[2 1] [2 2] [1 3]]
    _$W=               e# Copy elements:        | [[2 1] [2 2] [1 3]] [2 1]
       0=              e# First element:        | [[2 1] [2 2] [1 3]] 2
         \             e# Swap:                 | 2 [[2 1] [2 2] [1 3]]
          {0=1$=},     e# Filter where x[0]==2: | 2 [[2 1] [2 2]]
                  e~   e# RLE decode:           | 2 [1 1 2 2]
                    \; e# Delete back:          | [1 1 2 2]
                      }

仅当最小整数属于最常见的元素时,此方法才有效。您将需要$W=而不是第一个0=
Martin Ender

我添加了另一个可以接受的替代方法,它可以帮助您节省一些字节。
Leaky Nun

0

Clojure,65个字节

#(let[P partition-by C count](last(P C(sort-by C(P +(sort %))))))

取消高尔夫:

(def f #(->> %
             (sort-by      identity)   ; sort so that identical values are one after another, same as sort
             (partition-by identity)   ; partition by identity (duh!)
             (sort-by      count)      ; sort by item count
             (partition-by count)      ; partition by item count
             last))                    ; get the last partition

0

C#,145字节

l=>{var t=Enumerable.Range(0,l.Max()+1).Select(i=>l.Count(a=>a==i));return t.Select((a,i)=>Enumerable.Repeat(i,a)).Where(d=>d.Count()==t.Max());}

这也可能会更好,但是我有点卡住了。

说明

l =>                                                   //Takes the list
{                                                      //...
    var t = Enumerable.Range(0, l.Max() + 1)           //Makes a range till the count, so that the items together with their indices are double defined (i.e. the items are 0,1,2,3... and the indices are the same)
                      .Select(i =>                     //Takes the items
                          l.Count(a => a == i));       //And replaces them with the count of themselves in the list (so the item has the index with its old value and the count as it's actual value)
    return t.Select((a, i) =>                          //Then it takes this list and selects the items together with the indices
        Enumerable.Repeat(i, a))                       //Repeats them as often as they appeared in the list
                  .Where(d => d.Count() == t.Max());   //And just keeps those which appear the maximum amount of times
};                                                     //...

完全不同的方法可能要短得多,因此C#挑战仍然是可能的:)


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.