最長の等しいサブシーケンス


18

定義

  • サブシーケンスは連続していない場合があります。たとえば[1, 1, 1]、のサブシーケンスです[1, 2, 1, 2, 1]
  • 等しいサブシーケンスは、すべての要素が等しいサブシーケンスです。
  • 最長の等しいサブシーケンスは一意ではない場合があります。たとえば [1, 1][2, 2]の両方の最長等しいサブシーケンスです[2, 1, 1, 2]

入力

以下の形式のいずれかの正の整数の空でないリスト:

  • あなたの言語の正の整数の配列のネイティブ実装として
  • 改行で区切られた10進数の整数の文字列として
  • 改行で区切られた単項の整数の文字列として
  • その他の合理的な形式

出力

以下の形式のいずれかで、任意の順序で最長の等しいサブシーケンスのすべて:

  • 言語の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申し訳ありませんが、質問を編集しました。
リーキー修道女

出力に対してフラットリストは機能しますか?例えば1 2 31 1 2 21 1 2 21 1 1
コナーオブライエン

ConorO'Brien @ ...はい、ほとんどここに答えのを無効にすると言っ
漏れ修道女

@LeakyNunのように、それは許容可能な代替手段ですか?
コナーオブライエン

回答:


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.

私は...ゼリーが最大の速いを持っていないと思った
漏れ尼僧

技術的には最大の速さですが、はい、そうです。
デニス

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
ああ、もう一人のブラキロジスト。
リーキー修道女

1
どういうわけか、あなたと私はBrachylogチャットでお互いを繰り返し見逃していたに違いありません。私は何ヶ月もそれを使ってきましたが、明らかにFatalize以外の誰かもそうだったことを知って驚きました。

5

Pyth、5バイト

S.M/Q

テストスイート

説明:

これは暗黙的に行われS.M/QZQます。.Mは最大関数であるため、入力の要素の出現回数をカウントするの.M/QZQ値が最大であるすべての要素を選択します/QZS次に、同一の要素が連続するようにリストをソートします。


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
  }
'

オンラインでお試しください!

3バイトのLeaky Nunに感謝します!



説明を更新することを検討してください
リーキーヌン

3

パイソン268の 63バイト

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

オンラインでお試しください!


Python 3で回答をご覧ください:p
リーキーヌン

1
これを移植するのは簡単です。単にに置き換えprintてくださいreturn
デニス

ああ、私はPython 3にはないと思ったmap
リーキー修道女

3は少し異なります(3つ以上の引数がある場合、ジェネレーターを返し、より長いイテラブルを切り捨てます)が、そこにあります。
デニス

私は、Pythonが内蔵され、このためにと思っていた
ベータ崩壊を

2

Mathematica、42 31 25バイト

5バイトの@GregMartinと、もう1バイトの@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
マーティンエンダー

私はあなたがいくつかのバイトをオフにゴルフを助けるかもしれない別の許容可能な代替手段を追加しました。
リーキー修道女

2

スタック55 52 43バイト

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

オンラインでお試しください!

入力のランレングスエンコーディング、オカレンスによるソート、オカレンス数が最大になるオカレンスの保持、およびランレングスデコードによって機能します。チャレンジで受け入れられるように、フラットリストを介して出力します。


2

実際には、23バイト

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

オンライン試すかすべてのテストケースを実行してください

1バイトの改善点を指摘してくれた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
リーキー修道女

私はあなたがいくつかのバイトをオフにゴルフを助けるかもしれない別の許容可能な代替手段を追加しました。
リーキー修道女

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

私はあなたがいくつかのバイトをオフにゴルフを助けるかもしれない別の許容可能な代替手段を追加しました。
リーキー修道女

@LeakyNunお知らせいただきありがとうございます
ルイスメンドー

それは私の責任です。
リーキー修道女

1

オクターブ、47バイト

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

オンラインでお試しください!

説明

mode(として得られる[~,b,c]=mode(...))の2番目と3番目の出力は、それぞれ繰り返し数(b)とc、入力(input(0))で最も繰り返される要素の列セル配列()を提供します。次に、セル配列cが水平方向に繰り返されbrepmat(c,1,b))、コンマ区切りリストに変換され({:})、水平方向に汚染[...]され(disp(...))、数値マトリックスが表示されます()。


私はあなたがいくつかのバイトをオフにゴルフを助けるかもしれない別の許容可能な代替手段を追加しました。
リーキー修道女


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(ダイアログ)、22バイト

⎕ML←3多くのシステムでデフォルトである必要があります。

プログラム: s/⍨(⌈/=⊢)≢¨s←⊂⍨(⍋⊃¨⊂)⎕

 数値(評価済み)入力を取得する

() 暗黙の関数 は、配列全体  から選択する
 昇順アイテムのインデックスです。
⊃¨

⊂⍨ その増加で切断することによるパーティション

s← 店

≢¨ 集計する

() 暗黙の関数
⌈/ の最大値(タリー)
= は
 引数( タリー)に等しい

s/⍨ フィルタそれと

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

{} 引数が存在する匿名関数

⍵[⍋⍵] ソート(昇順アイテムのインデックス付きの点灯インデックス)

⊂⍨ その増加で切断することによるパーティション

s← 店

≢¨ 集計する

() 暗黙の関数
⌈/ の最大値(タリー)
= は
 引数( タリー)に等しい

s/⍨ それでフィルターs オンライン試しください!


私はあなたがいくつかのバイトをオフにゴルフを助けるかもしれない別の許容可能な代替手段を追加しました。
リーキー修道女

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)]);

オンライン版

出力フォーマット

1D Key = value

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));

私はあなたがいくつかのバイトをオフにゴルフを助けるかもしれない別の許容可能な代替手段を追加しました。
リーキー修道女

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))

テストケース


私はあなたがいくつかのバイトをオフにゴルフを助けるかもしれない別の許容可能な代替手段を追加しました。
リーキー修道女

@LeakyNun通知ありがとうございます。
アーナウド

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=
マーティンエンダー

私はあなたがいくつかのバイトをオフにゴルフを助けるかもしれない別の許容可能な代替手段を追加しました。
リーキー修道女

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#チャレンジはまだ開いています:)


弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.