카테고리 보관물: 코딩

코딩

절대 증폭 지그재그 첫 번째 N 번호를

양의 정수 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이전 피크 또는 최저점보다 라인이있는 라인에서 한 라인 더 떨어진 지점에 도달합니다 .

  • N은로 제한되지 않는다 44. 지그재그는 같은 패턴으로 자라며 더 큰 N이 지원되어야합니다.

  • 여러 자릿수가있는 숫자는 그림과 같이 모서리에서 “터치”해야합니다. N이 100이상일 때 이것이 작동하는지 확인하십시오 .

  • 선택적인 후행 줄 바꿈 하나를 제외하고 출력에 빈 (또는 공백 만) 줄이 없어야합니다.

  • 모든 행에는 임의의 양의 후행 공백이있을 수 있습니다.

채점

바이트 단위의 가장 짧은 코드가 이깁니다. Tiebreaker가 이전 답변입니다.



답변

젤리 , 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.


답변

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 : LAINT-1 문자 세트를 사용하도록 ~ õ로 바이트를 하나 더 절약하는 @Lynn의 조언에 따라. (온라인 PHP 에뮬레이터에서는 사용할 수 없으므로 포함되지 않음)


답변

Pyth, 60 53 52 46 42 39 38 36 34 32 31 바이트

39 : 이제 버그 수정 버전 인 Jelly 와 동등하며 Dennis의 경쟁 버전을 능가했습니다!

38 : 데니스를 아웃 골프했습니다!

36 : 데니스를 다시 골라 냈습니다!

34 : 버그 수정 버전보다 훨씬 낮습니다!

31:32-> 31 Dennis에게 감사합니다.

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 *] * dl`hkyh + 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.


답변

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),:),'']

MATLAB은 공백으로 색인 된 문자를 인쇄 0하지만 옥타브는 해당 문자를 생략하므로 옥타브 에서 공백이 누락되었습니다 .

설명:

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


답변

하스켈, 144142 바이트

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 감사합니다!


답변

자바 스크립트 (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`

어디 \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-=.


답변

파이썬 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 의 출력을 봅니다 .