永遠に増幅するジグザグ


24

正の整数Nを取り、必要な行のみを使用して、この増幅ジグザグパターンの最初のN個の数値を出力するプログラムまたは関数を記述します。

                                         26
                                       25  27                                      .
         10                          24      28                                  .
        9  11                      23          29                              .
 2     8     12                  22              30                          44
1 3   7        13              21                  31                      43
   4 6           14          20                      32                  42
    5              15      19                          33              41
                     16  18                              34          40
                       17                                  35      39
                                                             36  38
                                                               37

したがって、Nが1出力の場合

1

Nがの2場合、出力は

 2
1

Nが3出力の場合

 2
1 3

Nが4出力の場合

 2
1 3
   4

Nが10出力の場合

         10
        9
 2     8
1 3   7
   4 6
    5

Nが19出力の場合

         10
        9  11
 2     8     12
1 3   7        13
   4 6           14
    5              15      19
                     16  18
                       17

等々。

ノート

  • ジグザグの各ピークまたは谷は1、前のピークまたは谷よりも上にある線からもう1行離れた点に到達します。

  • Nはに限定されません44。ジグザグは同じパターンで成長し、より大きなNをサポートする必要があります。

  • 図のように、複数の数字がある数字は、角でのみ「触れる」必要があります。Nが100上記の場合、これが機能することを確認してください。

  • 1つのオプションの末尾の改行を除いて、出力には空(またはスペースのみ)の行がありません。

  • 任意の行に任意の量の末尾スペースを含めることができます。

得点

バイト単位の最短コードが優先されます。Tiebreakerは以前の回答です。


可能な最大Nは?
ジュリーペレティエ

@JuliePelletier理論上は何もありませんが、2 ^ 16未満になると想定できます。
カルビンの趣味

制御文字の使用は許可されていますか、または数字スペースと改行に制限されていますか?
デニス

2
@Dennisノーと言いましょう。数字/スペース/改行のみ。
カルビンの趣味

1
誰かがそれをジョークとしてその形式でOEISに提出するべきです。
DanTheMan

回答:


10

ゼリー41 37 29 バイト

RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷

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

使い方

RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷  Main link. Argument: n (integer)

R                              Range; yield [1, ..., n].
 D                             Decimal; yield A =: [[1], ..., [1, 0], ...].
  µ                            Begin a new, monadic chain. Argument: A
   Ḍ                           Undecimal; convert back to falt range.
    ’                          Decrement to yield [0, ..., n-1].
     ½Ċ                        Take the square root and round up (ceil).
       -*                      Elevate -1 to each rounded square root.
         _\                    Cumulatively reduce by subtraction.
                               This yields [1, 2, 1, 0, -1, 0, ...], i.e., the
                               vertical positions of the digits in A.
             L€                Compute the length of each list in A.
           x                   Repeat the nth position l times, where l is the
                               nth length.
            ©                  Copy the result to the register.
               Ṣ               Sort.
                .ị             At-index 0.5; yield the last and first element,
                               which correspond to the highest and lowest position.
                  ạ€®          Take the absolute difference of each position in the
                               register and the extrema.
                               This yields the number of spaces above and below
                               the integers in r as a list of pairs.
                     ⁶ẋ        Replace each difference with that many spaces.
                         F     Flatten the list A.
                       j"      Join the nth pair of strings of spacing, separating
                               by the nth digit in flat A.
                          Z    Zip/transpose the result.
                           j⁷  Join, separating by linefeeds.

2
あなたの言語(Jelly)で、それを実行している間にいくつかの文字でそれを行うことができる関数を作成してみませんか?
ジュリーペレティエ

19
@JuliePelletier優れたゴルフ言語を書く技術は、可能な限り多くの異なるタスクのための短いソリューションを書くことを可能にする一連の指示(および構文/言語セマンティクス)を考え出すことです。そして、シングルバイトでの人為的なチャレンジ。優れたゴルフ言語は、計算する特定の機能以外には役に立たない組み込みのコレクションであるだけでなく、実際には非常に強力で表現力豊かになる傾向があります。
マーティンエンダー

@JuliePelletierそしてそれはまた、PPCG SEの規則に反する
バリント

8

PHP、211の 177 164 163バイト

出力カーソル$nを使用して、どちらの方向でも動的にピークを予測し、配列を動的に増加させ($x, $y)ます。

数値は整列されstr_pad()、最終的な出力はそのimplode()文字列の配列($g)です。

for($x=0,$d=-1,$h=$n=2,$y=$a=1;$a<=$argv[1];$y+=$d){$g[$y]=str_pad($g[$y],$x).$a;$x+=strlen($a);if($a++==$n){$h+=2;$n+=$h-1;$d*=-1;}}ksort($g);echo implode(~õ,$g);

オンラインでテストしてください!

更新:不要なarray_pad()を削除して34バイトを削除しました。Update2:@insertusernameこちらのアドバイスに従い、もう少し短くします。Update3:LATIN-1文字セットの使用を強制する〜õでもう1バイトを保存する@Lynnのアドバイスに従いました。(オンラインPHPエミュレーターでは利用できないため、そこには含まれていません)


このコードに関する質問です。特定の要素にアクセスする前に、配列$ gを初期化する必要はありませんか?つまり、長さを指定するか、行を挿入しますか?私はPHPにあまり慣れていないので、奇妙に見えます...ありがとう。
ヨタムサーモン

いいえ。定義すると$arr = [];、を参照できます$arr[anything]。通知を出力する場合もありますが、ここでは無視します。このようなものを読むことは、おそらくあなたが言語を学ぶのにあまり役に立たないことに注意してください。あなたのコメントは、私が配列をパディングする必要があると最初は思っていたが、そうではないので、もっと短くできることに気づきました。:)
ジュリーペレティエ

ハハ、助けてくれて嬉しいです;)PHPでは、配列と辞書が同じ方法で初期化され、構文を見るとまったく同じであることに気付きました(なぜ、PHP ?!)
Yotam Salmon

いくつかのマイナーな改善– 164バイトfor($x=0,$d=-1,$h=$n=2,$y=$a=1;$a<=$argv[1];$y+=$d){$g[$y]=str_pad($g[$y],$x).$a;$x+=strlen($a);if($a++==$n){$h+=2;$n+=$h-1;$d*=-1;}}ksort($g);echo implode("⏎",$g);(⏎を実際の改行で置き換えます。)
insertusernamehere

エンコードの権利(UTF-8ではなく、Latin-1)を設定すると、2バイトの代替手段になると思います"⏎"
リン

8

Pyth、60 53 52 46 42 39 38 36 34 32 31バイト

39:バグ修正バージョンのJellyと同等になりました。私は、デニスの競合バージョンを凌haveしています!

38:デニスをゴルフアウトしました!

36:デニスを再びゴルフアウトしました!

34:バグ修正版よりもさらに低い!

31:32-> 31デニスに感謝します。

J1K.u+N=J_WsI@Y2JtQZjsM.t.e ++ *] * dl`hkabhSK`hk *] * dl`hkabeSKKd 
J1K.u+N=J_WsI@Y2JtQZjsM.t.eX *] * dl`hkhaeSKhSKabhSKhkKd 
J1K.u + N=J_WsI@Y2JtQZ=-RhSKKjsM.t.eX *] * dl`hkheSKbhkKd 
J1K.u+N=J_WsI@Y2JtQQj-#dsMC.eX *] * dl`hkheSKbhkK 
J1j-#dsMC.eX *] hdldl + Qbhkm = + Z = J_WsI @ td2J 
J1j-#dsMCmX *] *; l`hdyQ + Q = + Z = J_WsI @ td2Jhd 
J1j-#dsMCmX *] *; l`hdyQ + Q = + Z = J_WsI @ td2Jh 
J1j -#dsMCmX *] *; l`hdyQ + Q = + Z = @ _ BJsI @ td2h 
j-#dsMCmX *] *; l`hdyQ + Q = + Zsty%s @ td2 2h 
j-#dsMCmX *] *; l `hdyQ + Q = + Z @ _B1.E @ d2h 
JQj-#dsMCmX *] *; l`hdyQ = + J @ _B1.E @ d2h 
JyQj-#dsMCmX *] *; l`hdJ = + Q @ _B1。 E @ d2h 
j-#dsMCmX *] *; l`hdyQ = + Q @ _B1.E @ d2h
j-#dsMCmX *] *; l`hdyQ=+Q^_1.E@d2h

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

使い方

j-#dsMCmX*]*;l`hdyQ=+Q^_1.E@d2h      input: Q
j-#dsMCmX*]*;l`hdyQ=+Q^_1.E@d2hdQ    implicit filling arguments

       m                        Q    for each number d from 0 to Q-1:
                           @d2           yield the square root of d.
                         .E              yield its ceiling.
                      ^_1                raise -1 to that power. this
                                         yields the desired direction.
                   =+Q                   increment Q by this amount.

               hd                        yield d+1.
              `                          yield its string representation.
             l                           yield its length.
           *;                            repeat " " for that number of times
          ]                              yield a list containing the string above.
         *       yQ                      repeat the list for Q*2 times.
                                         the Q has changed, but Q*2 is
                                         an overshoot that is high
                                         enough, so we don't have to
                                         worry about it.

        X                                in that list, replace the
                                         element with index being the
                                         number generated above
                              hd         with d+1.

      C                              transpose the resulting array.
    sM                               flatten each element.
 -#d                                 remove lines containing only spaces.
                                     (filter on truthiness of set difference with space)
j                                    join by newlines.

2
39:ゼリーと同等」「38:デニスをゴルフアウトしました!」あなたは数時間あなたがしましたが、@ Dennisはコードゴルフでbeatられたくないようです:Jelly 37バイト ;)
ケビン・クルーセン

1
@KevinCruijssen完了
漏れの修道女

いいね!xDM̶a̶y̶b̶e̶私は想像力に富んでいますが、この短いソリューションが見つかるまで何時間も欲求不満で見つめ続けてきたと思います。(Jk、デニスの下にとどまることを望みます!)
ケビンCruijssen

@KevinCruijssen多田!バグ修正バージョンよりも低くなりました。
リーキー修道女

5

MATLAB、148バイト

n=input('');k=fix(n^.5);m=0;w=1;d=-1;for l=1:n;s=num2str(l);m(k+1,w:w+nnz(s)-1)=s;w=w+nnz(s);k=k+d;d=d*(-1)^(l^.5==fix(l^.5));end;[m(any(m,2),:),'']

Octaveではスペースが欠落していることに注意してください。MATLABはインデックス付きの文字を0スペースとして出力しますが、octaveはその文字を省略します。

説明:

n=input('');
k=fix(n^.5);                    %caculate starting height
m=0;w=1;d=-1;                   %initialize counters and output matrix
for l=1:n;
    s=num2str(l);
    m(k+1,w:w+nnz(s)-1)=s;      %insert current index as a string
    w=w+nnz(s);                 %current horizontal position
    k=k+d;                      %current vertical position
    d=d*(-1)^(l^.5==fix(l^.5)); %if we reached a square number, change direction
end
[m(any(m,2),:),'']              %delete all zero rows

3

ハスケル、144 142バイト

g n|k<-take n$scanl(+)0$[1..]>>= \x->(-1)^x<$[2..2*x]=unlines[[1..n]>>= \x->show x#(k!!(x-1)==y)|y<-[minimum k..maximum k]]
s#g|g=s|1<2=' '<$s

使用例:

*Main> putStr $ g 19
         10                  
        9  11                
 2     8     12              
1 3   7        13            
   4 6           14          
    5              15      19
                     16  18  
                       17    

使い方:

s#g|g=s|1<2=' '<$s              -- # is a helper function that expects a string s
                                -- and a boolean g. It returns s if g is True, else
                                -- as many spaces as there a characters in s 

k<-take n$                      -- bind k to the first n elements of
 [1..]>>= \x->(-1)^x<$[2..2*x]  -- 2*x-1 copies of (-1)^x for each x in [1,2,3,...]
                                -- i.e. [-1, 1,1,1, -1,-1,-1,-1,-1, 1,1,1,1,1,1,1..]
 scanl(+)0                      -- build partial sums, starting with 0
                                -- i.e. [0,-1,0,1,2,1,0,-1,-2,-3,-2,-1...]
                                -- -> k is the list of y coordinates for the
                                --    numbers 1,2,3,...

 [  |y<-[minimum k..maximum k]] -- for all y coordinates in k 
      \x->show x#(k!!(x-1)==y)  -- map the # function
  [1..n]>>=                     -- over [1..n] (the x coordinates)
                                -- where # is called with
                                --  s -> a string representation of x 
                                --  g -> True if k at index x equals the current y
unlines                         -- join with newlines

編集:2バイトありがとう@Lynn!


2

JavaScript(ES6)、213バイト

with(Math)n=>(a=[...Array(n)].map((_,i)=>n-=1+sqrt(--i)&1||-1).map((e,_,a)=>e-min(...a))).map((e,i)=>r[e][i]=++i,r=[...Array(1+max(...a))].map(_=>a.map((_,i)=>` `.repeat(1+log10(++i)))))&&r.map(a=>a.join``).join`\n`

where \nはリテラルの改行文字を表します。説明:

with(Math)                          Bring functions into scope
 n=>                                Accepts one parameter
  (a=                               Intermediate result variable
   [...Array(n)].map(               For each number 0..n-1
    (_,i)=>n-=                      Accumulate index for each number
     1+sqrt(--i)&1||-1              Calculate the direction
    ).map((e,_,a)=>e-min(...a))     Scale the smallest index to zero
  ).map((e,i)=>r[e][i]=++i,         Overwrite the padding with 1..n
   r=[...Array(1+max(...a))].map(   Calculate number of lines
    _=>a.map((_,i)=>                For each number 1..n
     ` `.repeat(1+log10(++i)))))    Calculate the padding needed
  &&r.map(a=>a.join``).join`\n`     Join everything together

短くするためpow(-1,ceil(sqrt(i)))にこれを書き直しますがsqrt(i-1)&1||-1、これはi=01を追加することを修正するために機能しませんが、これは結果の符号を反転させn-=ます。


こんにちは、あなたはゴールドバッジを手に入れました!良くやった!そして聖なる煙はあなたが私と同じくらい多くの担当者を持っています。続けて!
コナーオブライエン

1
@CᴏɴᴏʀO'Bʀɪᴇɴそれは「単なる」ファナティックバッジです。どうやら、ゴールドコードとゴルフのタグバッジを取得することに本当に近づいているようです!
ニール

聖なる二重煙。XDを動かす必要があります
コナーオブライエン

1

Python 2、137バイト

l={}
i=x=y=n=v=0
exec"v+=1;l[y]=l.get(y,'').ljust(x)+`v`;x+=len(`v`);i=-~i%-~n;y+=n%4-1;n+=2>>i*2;"*input()
for k in sorted(l):print l[k]

ideoneの出力を表示します。


うーん...それはずっと続きません。
Zizouz212

@ Zizouz212それは、ideoneは固定出力を備えており、長すぎる行を自動的に中断します。
-flawr
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.