シーケンスステップを取得する


17

チャレンジ

一連の数字が与えられたら、一連のステップを返す関数を作成します。

  • シーケンスは次のようになります N >= 3
  • シーケンスは少なくとも1回ステップを繰り返します
  • シーケンスには自然数のみが含まれます
  • 関数またはプログラムは、可能な限り短い手順のシーケンスを返す必要があります

例:

入力: [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17]

出力: [1, 1, 2]

説明:初期シーケンスはから始まります1 => 2 (1 step), 2 => 3 (1 step), 3 => 5 (2 steps)。その後、繰り返します。出力は[1 step, 1 step, 2 steps] => [1, 1, 2]

もう一つの例:

入力: [2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20]

出力: [3, 1, 1, 1]

[2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20]
 \  /\ /\ /\ / 
  3   1  1  1  Then it repeats...

テストケース

Input: [1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28] => Output: [3,4,1,1]

Input: [6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41] => Output: [5,2]

Input: [2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47] => Output: [4,4,3,4]

Input: [5, 6, 7] => Output: [1]


明確化

  • 入力長-1は出力長で割り切れます
  • シーケンスは常に増加すると想定します

これはであるため、バイト単位の最短回答が勝ちます。



6
最近、あなたが投稿したいくつかの課題に明確なコメントがたくさんあり、いくつかは「不明」として閉じられ、適切な編集を行った後に再び開かれました。これらを1週間に数日間、サンドボックスに投稿することを検討しましか?あなたの挑戦は非常に親しみやすいので楽しんでいますが、すべての挑戦は、どんなに単純で、誰によって投稿されたとしても、洗練を使用することができます。
ジュゼッペ

2
@Giuseppeご提案ありがとうございます。サンドボックスに他のいくつかのチャレンジを投稿しました(通常、チャレンジを作成する正しい方法が得られない場合は削除します)。これらの課題については、それらは十分に明確であると思ったので、すぐに投稿しましたが、最初にサンドボックスに投稿し始めます。ありがとう
ルイス・フェリペ・デ・イエス・ムニョス

2
@LuisMendo異端者!0は自然数です!ビリー・ジョエルはペアノマンに捧げられたアルバム全体を持っていました!
ngm

1
@AdmBorkBork、これは、任意の長さの操作リストを処理することにより、より関連しています。
ピーターテイラー

回答:


10

ゼリー9 7バイト

IsJEƇḢḢ

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

使い方

IsJEƇḢḢ  Main link. Argument: A (array)

I        Increment; compute D, the array of A's forward differences.
  J      Indices; yield [1, ..., len(A)].
 s       Split D into chunks of length k, for each k in [1, ..., len(A)].
   EƇ    Comb equal; keep only partitions of identical chunks.
     Ḣ   Head; extract the first matching parititon.
      Ḣ  Head; extract the first chunk.

9

JavaScript(ES6)、58バイト

コンマで区切られた文字列を出力します(先頭にコンマが付きます)。

a=>(a.map(p=x=>-(p-(p=x)))+'').match(/N((,\d+)*?)\1*$/)[1]

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

または、セパレータとして使用し、シーケンスが常に厳密に増加していると仮定した場合、56バイト,-

どうやって?

最初に、入力配列a []を連続した差異のリストに変換します:

a.map(p = x => -(p - (p = x)))

pは最初は非数値(map()のコールバック関数)に設定されているため、最初の反復でNaNが生成されます。

例:

[6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41]
[ NaN, 5, 2, 5, 2, 5, 2, 5, 2, 5, 2 ]

次に、結果を文字列に強制します。

"NaN,5,2,5,2,5,2,5,2,5,2"

最後に、「NaN」の直後から文字列の最後まで繰り返す、カンマ区切り整数()の最短1パターンを探し,\d+ます。

match(/N((,\d+)*?)\1*$/)

1:非欲張りの使用 *?


私は同じ正規表現のアイデアに基づいたソリューションを投稿していますが、実装は非常に異なります。もちろん、鉱山を開発する前に他のソリューションを検討したことはありませんでしたが、それは十分に異なっているようです。
edc65

1
53バイト:/(,.+?)\1*$/
ニール

6

Brachylog、11バイト

s₂ᶠ-ᵐṅᵐ~j₍t

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

連続した差異の組み込みがあった場合、5バイトになります。

説明

Example input: [6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41] 

s₂ᶠ             Find all substrings of length 2: [[6,11],[11,13],…,[34,39],[39,41]]
   -ᵐ           Map subtraction: [-5,-2,-5,-2,-5,-2,-5,-2,-5,-2]
     ṅᵐ         Map negate: [5,2,5,2,5,2,5,2,5,2]
       ~j₍      Anti-juxtapose the list of differences; the shortest repeated list is found
                  first, with the biggest number of repetitions: [5,[5,2]]
            t   Tail: [5,2]

バイトを節約するために、テールの後に否定できますか?
ロッド

@Rodまだマップする必要があるので、同じ長さになります。否定は2つの数値間の述語であり、他の言語のようなリストに自動的にベクトル化されません(宣言型プログラムで一般的な未知の入力/出力ではうまく機能しません)
Fatalize

5

Pyth、11バイト

<J.+Qf.<IJT

ここで試してみてください

説明

<J.+Qf.<IJT
 J.+Q          Call the sequence of differences in the input J.
     f         Find the first positive integer T...
      .<IJT    ... where rotating J by T doesn't change it.
<J             Take that many elements of J.


5

R49 46バイト

完全なプログラム:

d=diff(scan());while(any((s=d[1:T])-d))T=T+1;s

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

R72 58 54バイト

1つの場所にすべてのテストケースを含む元の関数の送信:

function(a,d=diff(a)){while(any((s=d[1:T])-d))T=T+1;s}

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

完全なプログラムルートと関数の-4バイトを提案してくれたJayCe、さらに-3をくれたGiuseppeに感謝します。


-9悪用によりバイトを内蔵し、それ完全なプログラム作りの課題は、完全なプログラムを可能にします。
JayCe

@JayCeもa<-ここでは必要ありません
ジュゼッペ

4

J22 19バイト

FrownyFrogのおかげで3バイト節約されました!

0{"1[:~./:|."{}.-}:

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

[オンラインで試す!] [TIO-ji2uiwla]

どうやって?

                 -      find the successive differences by subtracting 
                  }:    the list with last element dropped
               }.       from the list with the first element dropped 
           |."{         rotate the list of differences
         /:             0..length-1 times (the input graded up)
     [:~.               remove duplicating rows
 0{"1                   take the first element of each row

/:代わりに1バイトを節約#\でき0{"1[:~.ます。
FrownyFrog

そして"0 1ある"{
FrownyFrog

@FrownyFrogありがとう、もう一度!
ガレンイワノフ

1
これは素晴らしいです。
ヨナ

@ジョナはい、FrownyFrogのおかげで!
ガレンイワノフ

4

05AB1E、8バイト

Kevin Cruijssenのおかげで3バイト節約されました

¥.œʒË}нн

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


05AB1E、11バイト

āεI¥ô}ʒË}нн

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

āεI¥ô}ʒË}нн全プログラム。
ā長さの範囲。[1 ... len(inp)]を押します。
 ε}それぞれ...
  I¥ô...デルタを対応するサイズの断片に切り刻みます
      ʒË}すべての要素が等しいもののみを保持します。
         ннそして、最初に最初の要素の最初の要素を取得します。

13バイト

かわいい代替、IMO:

¥©ηʒDg®ôÙ˜Q}н

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

¥©ηʒDg®ôÙ˜Q}н   Full program.
¥               Push the deltas.
 ©              Copy them to the register.
  ηʒ       }    And filter the prefixes by...
    D     Q     ... Is the prefix itself equal to...
     g®ô        ... The deltas, split into chunks of its length...
        Ù˜      ... Deduplicated and flattened?
            н   Head.

1
を使用して 8バイト
ケビンクルーッセン

3

Javascript、49 56バイト

編集 7バイトのおかげで保存(だれか?)Arnauld

Arnauldと同じ正規表現のアイデアですが、奇妙なことに実装がまったく異なります...

ステップをコンマで区切った文字列(および先頭のコンマ)を返す

p=>/N(.+?)\1+$/.exec(p.map(p=v=>[v-p,p=v][0]))[1]

テスト

var F=
p=>/N(.+?)\1+$/.exec(p.map(p=v=>[v-p,p=v][0]))[1]

;[[1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17]
,[1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28]
,[6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41] 
,[2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47]
,[5, 6, 7]]
.forEach(x=>console.log(x + ' -> ' + F(x)))


使用することmatchは、私の悪い決断でした。あなたは私にもう少しゴルフをすることができます。:-)
アーナウルド

3

MATL14 13 12バイト

dt5YLFTF#Xu)

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

MATLには循環機能があることがわかりました!

説明

d -連続する用語間の差を配列として取得する

t5YL-それを複製して、( 'circulant')オプションを指定してYL( 'gallery')関数を呼び出し5ます。指定されたベクトルを最初の行として行列を作成します。その後、連続する行は、循環するまで同じベクトルを循環的にシフトします。

FTF#Xu-一意の行を確認し、行番号を取得します(これを行う短い方法があるかどうかはわかりません)。シーケンスのステップが繰り返されると、循環シフトされた行は最初の行と同じになり、後続の行が繰り返されます。そのため、これはシーケンスステップの最初の実行のインデックスを取得してから、繰り返し始めます。

) -それを使用して元の差分配列にインデックスを付け、答えを取得します。


古い:

d`tt@YS-a}@:)

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

(ジュゼッペのおかげで1バイト)

説明:

d   % Get the differences between successive terms, as an array
`   % Start do-while loop
  tt  % duplicate the difference array twice
  @   % push the current loop index value
  YS  % circularly shift the difference array by that amount
  -   % subtract the shifted diffs from the original diffs
  a   % see if the subtraction resulted in any non-zeros
    % if it did, shifted differences were not equal to original differences, so continue loop 
}@ % if it didn't, then get loop index
:) % get the differences upto the loop index, before they started repeating
   % implicit loop end

2

Python 2、101バイト

def f(l):d=[y-x for x,y in zip(l,l[1:])];g=len(l);print[d[:k]for k in range(1,g+1)if g/k*d[:k]==d][0]

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

最初のデルタを生成dは、最初プレフィックス発見PDの場合を繰り返すこと(L)/ lenの(P)⌋⌊len回収率のLLは、入力リストです。



2

Java 10、104 100バイト

a->{var t="";for(int i=a.length;i-->1;t+=a[i]-a[i-1]+" ");return t.replaceAll("( ?.+?)\\1*$","$1");}

正規表現( ?.+?)\1*$最短用から部分繰り返し@Neil「に関するコメントの@Arnauld秒のJavaScript(ES6)の答え」

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

説明:

a->{                        // Method with integer-array parameter and String return-type
  var t="";                 //  Temp-String, starting empty
  for(int i=a.length;i-->1; //  Loop backward over the input-array, skipping the first item
    t+=a[i]-a[i-1]          //   Calculate the difference between two adjacent items
       +" ");               //   And append this with a space to the temp-String
  return t.replaceAll("( ?.+?)\\1*$", 
                            //  Find the shortest repeating substring
                     "$1");}//  And only keep one such substring

1

APL + WIN、39バイト

入力を要求します。

(↑((⍴v)=+/¨(⊂v)=(⍳⍴v)⌽¨⊂v)/⍳⍴v)↑v←-2-/⎕

オンラインでお試しください!Dyalog Classic提供

説明:

v←-2-/⎕ Prompt for input and take successive differences

(⍳⍴v)⌽¨⊂v create a nested vector ans sequentially rotate by one to length of v

+/¨(⊂v)= compare to original v and sum positions where there is match

(⍴v)= identify where all elements match

(↑(....) identify number of rotations giving a first complete match

(↑(...)↑v take first number of elements from above from v as repeated sequence


1

Retina 0.8.2、42バイト

\d+
$*
(?<=(1+),)\1

1+(.+?)\1*$
$1
1+
$.&

オンラインでお試しください!リンクにはテストケースが含まれます。出力には、先頭のコンマが含まれます。説明:

\d+
$*

単項に変換します。

(?<=(1+),)\1

前方差分を計算します。ただし、最初に残された数値を除きます。

1+(.+?)\1*$
$1

繰り返しの違いに一致します。

1+
$.&

10進数に変換します。


1

05AB1E14 13 バイト

¥DηvÐNƒÁ}QD—#

オンラインそれを試してみたり、すべてのテストケースを確認してください

@ Mr.Xcoderによって投稿された2つの短い05AB1E回答が既にあることは知っていますが、回転と等価性チェックを使用するこの代替アプローチを試してみたかったのです。
数バイト落とさずにゴルフできるかもしれませんÁ

@Emignaの先端の後の-1バイトでglobal_variableレジスタ(©および2x ®)を削除し、代わりにDuplicate(D)およびTriplicate()を使用しÐます。

説明:

¥             # Calculate the deltas of the input-array
              #  i.e. [1,2,3,5,6,7,9] → [1,1,2,1,1,2]
 D            # Duplicate it
  η           # Push all its prefixes
              #  [1,1,2,1,1,2] → [[1],[1,1],[1,1,2],[1,1,2,1],[1,1,2,1,1],[1,1,2,1,1,2]]
v             # For-each over these prefixes
 Ð            #  Triplicate the (duplicated) deltas-list
  NƒÁ}        #  Rotate the deltas-list N+1 amount of times,
              #  where N is the prefix index (== prefix_length-1)
              #   i.e. [1,1,2] and [1,1,2,1,1,2] (rotate 3 times) → [1,1,2,1,1,2]
      Q       #  If the rotated deltas and initial deltas are equal
              #   [1,1,2,1,1,2] and [1,1,2,1,1,2] → 1
       D—#    #  Print the current prefix-list, and stop the for-each loop

1
ここに9があります(アルゴは非常に異なるため、個別の回答ですが、¥ηを共有しています)。
グリムミー

@Grimy 05AB1Eのすべての答えを調べて、それぞれをゴルフしていますか?; pいい答え(まだ)、私から+1。
ケビンクルーッセン

1
それらのすべてではなく、この投稿にリンクされているものだけを見ていきます。
グリムミー

@Grimy Ah ok、それは理にかなっています。:)
ケビンクルーイセン

1

Haskell、107バイト

let i=map(uncurry(-))$zip(tail x)(init x)in head$filter(\s->take(length i)(concat$repeat s)==i)(tail$inits i)

xは入力配列です。


特にPPCGとHaskellゴルフへようこそ!入力が特定の変数に存在すると想定することはできませんが、これはprependingで簡単に修正できf x=ます。またの使用がinits必要ですimport Data.List:プレリュードの一部ではないとして、オンラインそれをお試しください!
ライコニ

ただし、かなりのバイト数を節約できます。リストの1つが他のリストより長い場合に自動的に切り捨て(init x)られるxからzipです。また、次のmap(uncurry(-))$zipビルドインが存在しますzipWith(-)。代わりにf x=let i=...in、パターンガードを使用できますf x|i<-...=
ライコニ

さらに、あなたの代わりにリストの内包表記を使用することができfilter!!0代わりにheadcycleの代わりconcat$repeatオンラインそれをお試しください!
ライコニ

@Laikoni改善してくれてありがとう!私のコードには、関数宣言とData.List.initsのインポートが必要です。しかし、私はそれをコードの長さに追加すべきかと思っていましたか?他のコードサンプルのいくつかが同様にいくつかの追加コードに依存しているため、私は尋ねています。
misja111

はい、これらのバイトがスコアに含まれることは一般的なコンセンサスです。我々は持っているHaskellではゴルフのルールにガイドこれらのケースのほとんどをカバーしています。
ライコニ


1

Perl 6、57バイト

{~(.rotor(2=>-1).map:{.[1]-.[0]})~~/^(.+?){}" $0"+$/;~$0}

試して

出力はスペースで区切られます("1 1 2"

拡張:

{      # bare block lambda with implicit parameter $_

  ~(   # stringify (space separated)

    .rotor( 2 => -1 )     # from the input take 2 backup 1, repeat
    .map: { .[1] - .[0] } # subtract each pair to find the differences
  )

  ~~   # smartmatch

  /    # regex

    ^  # beginning of string

    ( .+? ) # match at least one character, but as few as possible
    {}      # make sure $0 is set (probably a compiler bug)
    " $0"+  # match $0 one or more times (with a leading space)

    $  # end of string
  /;

  ~$0  # return the stringified $0
}

全体の最初の部分は次のようになります~(.skip Z-$_)
ジョーキング

1

05AB1E、9バイト

¥©η.ΔÞ®Å?

説明:

          # take input implicitly
¥         # deltas, eg [4, 5, 7, 8, 10] -> [1, 2, 1, 2]
 ©        # save this to the global register
  η       # prefixes, eg [1, 2, 1, 2] -> [[1], [1, 2], ...]
   .Δ     # find the first one such that
     Þ    # cycled infinitely, eg [1, 2] -> [1, 2, 1, 2, ...]
       Å? # starts with
      ®   # the global register
          # and implicitly print the found element

代替の9バイト:

¥η.ΔÞ.¥-Ë

同じアルゴリズムですが、(保存/復元する必要がある)デルタのリストと比較する代わりに、(undelta)を使用して(暗黙の)入力と比較します。

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


0

K4、30バイト

解決:

(*&d~/:c#'(!c:#d)#\:d)#d:1_-':

例:

q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20
3 1 1 1
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17
1 1 2
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28
3 4 1 1
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41
5 2
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47
4 4 3 4
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':5 6 7
,1

説明:

私たちが解決しようとしていることは多額のようです。入力のデルタを取得し、シーケンスを構築して、それに一致する最短のデルタを決定します。

(*&d~/:c#'(!c:#d)#\:d)#d:1_-': / the solution
                           -': / deltas 
                         1_    / drop first
                       d:      / save as d
                      #        / take (#) from
(                    )         / do this together
                 #\:d          / take (#) each-left (\:) from d
          (     )              / do this together
              #d               / count length of d
            c:                 / save as c
           !                   / range 0..c-1
       c#'                     / take c copies of each
   d~/:                        / d equal (~) to each right (/:)
  &                            / where true
 *                             / first one


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