"친근한 펠릿"으로 줄을 감싼다

Sep 07 2020

문자열을 입력하고 "친근한 펠릿"을 번갈아 가며 둥근 사각형으로 둘러 쌉니다. ( 0)

모래 상자

Lyxal의 아이디어 .

도전

길이가 비어 있지 않은 한 줄의 문자열 \$<100\$, 그 0주위에 펠릿 ( ) 이 번갈아 가며 둥근 사각형으로 문자열을 인쇄합니다 .

직사각형의 높이는 11 줄이어야합니다.

직사각형의 첫 번째 줄에는 최소 1 개의 펠릿이 있어야합니다 .

직사각형의 중간 줄은 13 자 이상이어야합니다. 텍스트의 각면에 하나의 여백이 있어야합니다.

9 자보다 작은 문자열은 위의 사양에 맞도록 양쪽에 균등하게 공백을 채워야합니다. 문자열의 길이가 짝수 인 경우 오른쪽에 하나의 추가 공간이 허용됩니다.

출력 템플릿은 다음과 같습니다.

      00000..... 6 spaces
    0 4 spaces 
  0   2 spaces
 0    1 space
0     no spaces

문자열의 길이가 9보다 크거나 같으면; 첫 번째 줄에는 \가 있어야합니다.$\text{length}-8\$ 알약.

입력 및 출력 예

입력 :

안녕하세요!

출력 :

       0000  
     0      0  
   0          0
  0            0
 0              0
 0 Hello World! 0
 0              0
  0            0
   0          0
     0      0
       0000

입력

0

산출

       0
     0   0  
   0       0
  0         0
 0           0
 0     0     0
 0           0
  0         0
   0       0
     0   0
       0

입력

빠른 갈색 여우

산출

       00000000000 
     0             0  
   0                 0
  0                   0
 0                     0
 0 the quick brown fox 0
 0                     0
  0                   0
   0                 0
     0             0
       00000000000

입력

이 세상에서 KILL or BE kill

산출

      00000000000000000000000000000
    0                               0
  0                                   0
 0                                     0
0                                       0
0 In this world, it's KILL or BE killed 0
0                                       0
 0                                     0
  0                                   0
    0                               0
      00000000000000000000000000000

입력

안녕

산출

      0
    0   0
  0       0
 0         0
0           0
0 hi there  0
0           0
 0         0
  0       0
    0   0
      0

Ruby의 예제 코드

온라인으로 시도하십시오!

a=[4,2,1,0] # space length to create circle

str=gets.chomp;
l = str.length;
# print first line of pellets
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end
    
# initial pattern
for n in a do 
    print " "*n +"0"+" "*(5-n)
    print " " if l<=9
    print " "*(l-8) if l>9
    puts " "*(5-n) +"0"

end
    
# display string with spaces
if l<9 then puts "0"+" "*((11-l)/2).floor + str + " "*((12-l)/2).ceil + "0" else puts "0 #{str} 0" end

#initial pattern but reversed
for n in a.reverse do 
    print " "*n +"0"+" "*(5-n)
    print " " if l<=9
    print " "*(l-8) if l>9
    puts " "*(5-n) +"0"
end
    
# last line(same as first line)
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end


득점

이것은 code-golf 입니다. 각 언어에서 가장 짧은 답변이 이깁니다.

답변

8 Neil Sep 07 2020 at 16:04

목탄 , 40 바이트

≔⌈⟦¹⁻Lθ⁸⟧η×η0↘↘0→↘00↓00‖OO←η‖O↓J⊘⁻⊖ηLθ⁵θ

온라인으로 시도하십시오! 링크는 자세한 코드 버전입니다. 설명:

≔⌈⟦¹⁻Lθ⁸⟧η

0맨 위 행 의 s 수를 계산하십시오 .

×η0

인쇄하십시오.

↘↘0→↘00↓00

나머지 0는 오른쪽에 인쇄하십시오 .

‖OO←η

0s의 맨 위 행 0을 자체 위에 겹쳐서 s 의 추가 행을 왼쪽에 반영합니다 .

‖O↓

0가운데 줄과 겹치는 s를 아래쪽으로 반사하십시오 .

J⊘⁻⊖ηLθ⁵θ

텍스트의 위치를 ​​계산하고 거기에 인쇄하십시오. 이것은 짧은 문자열에 필요하지만 겹쳐진 반사가 커서를 잘못된 위치로 이동시키는 Charcoal 버그를 처리하는 것을 방지합니다.

6 Arnauld Sep 07 2020 at 15:53

자바 스크립트 (ES6)  152 139 134  133 바이트

s=>'64210~01246'.replace(/./g,k=>(g=i=>--i?(d=i+~k,d*=L-i+~k,s[k>g&&(L+n>>1)-i]||d&&k^6|d<0&&' ')+g(i):`
`)(L=(n=s.length)>9?n+5:14))

온라인으로 시도하십시오!

어떻게?

길이가 \ 인 입력 문자열이 주어지면$n\$, 우리는 \$L=\min(14,n+5)\$. 라인 피드를 포함하여 ASCII 아트 행의 너비입니다.

각 줄에 대해 \ 에 선행 공백 수를 저장합니다.$k\$\ 에서 반복$i=L-1\$\$i=1\$. 우리는 \$d=(i-k-1)\times(L-i-k-1)\$ 어떤 캐릭터를 그려야하는지 알아 내기 위해.

우리는 항상 경우 공간을 그릴 \$d\$\ 이면 음수이고 0입니다.$d=0\$. 만약 \$d\$양수이면 \$k=6\$(상단 및 하단 테두리) 또는 공백 (안쪽 셀). 중간 줄은 \ 위치에있는 입력 문자열에서 문자를 가져 오려고하는 특수한 경우입니다.$\lfloor (L+n)/2\rfloor-i\$.

를 들어 "Hello World!", 우리가 \$n=12\$\$L=17\$. 이것은 다음을 제공합니다.

    1      0  
i = 6543210987654321
    ------0++0------  k = 6
    ----0++++++0----  k = 4
    --0++++++++++0--  k = 2
    -0++++++++++++0-  k = 1
    0++++++++++++++0  k = 0
    0+Hello World!+0  k = 0
    0++++++++++++++0  k = 0
    -0++++++++++++0-  k = 1
    --0++++++++++0--  k = 2
    ----0++++++0----  k = 4
    ------0++0------  k = 6

댓글 작성

s =>                         // s = input string
'64210~01246'.replace(       // replace in the string '64210~01246'
  /./g, k => (               // each character k:
    g = i =>                 //   g is a recursive function taking a counter i:
      --i ?                  //     decrement i; if it's not 0:
        ( d = i + ~k,        //       d = i - k - 1
          d *= L - i + ~k,   //       d = (i - k - 1) * (L - i - k - 1)
          s[                 //       extract from s:
            k > g &&         //         if k is '~':
            (L + n >> 1) - i //           use floor((L + n) / 2) - i
                             //         otherwise, use false
                             //         (leading to s[false] == undefined)
          ]                  //       end of lookup in s
          ||                 //       if it's undefined:
            d &&             //         use '0' if d = 0
            k ^ 6 | d < 0    //         or k is equal to 6 and d is non-negative
            && ' '           //         otherwise, use a space
        ) + g(i)             //       append the result of a recursive call
      :                      //     else:
        `\n`                 //       append a linefeed and stop the recursion
  )(                         //   initial call to g:
    L = (n = s.length) > 9 ? //     if the length n of s is greater than 9:
      n + 5                  //       define L = n + 5
    :                        //     else:
      14                     //       define L = 14
  )                          //
)                            // end of replace()
5 KevinCruijssen Sep 07 2020 at 16:38

05AB1E , 64 54 바이트

4Å0Îg9‚à8-©;îךŽüÎSú.B®Éi.ºëº}I11Ig-;1‚à©ú®îð׫0.øª».∊

온라인으로 시도 하거나 모든 테스트 사례를 확인하십시오 .

설명:

4Å0                   # Push a list of 4 0s: [0,0,0,0]
   Î                  # Push 0 and the input-string
    g                 # Pop the input, and push its length
     9‚à              # Pair with 9, and pop and push the maximum
        8-            # Subtract 8
          ©           # Store this in variable `®` (without popping)
           ;          # Halve it
            î         # Ceil it
             ×        # Create a string of that many 0s
              š       # Prepend it at the front of the [0,0,0,0]-list
ŽüÎ                   # Push compressed integer 64210
   S                  # Convert it to a list of digits: [6,4,2,1,0]
    ú                 # Pad that many leading spaces to the list of 0s
.B                    # Box it, which adds trailing spaces to each string to equal
                      # their lengths
®Éi                   # If the value `®` is odd:
   .º                 #  Mirror each line with the last character overlapping
  ë                   # Else (it's even instead):
   º                  #  Mirror each line without overlapping
  }                   # Close the if-else statement
I                     # Push the input-string again
 11                   # Push 11
   Ig-                # Subtract the input-length from it
      ;               # Halve it
       1‚à            # Pair with 1, and pop and push the maximum
          ©           # Store it in variable `®` (without popping)
           ú          # Pad that many leading spaces to the input
            ®         # Push `®` again
             î        # Ceil it
              ð׫     # Pad that many trailing spaces
                 0.ø  # Then surround it with leading/trailing 0
                    ª # And append it to the list of strings
»                     # Join the lines by newlines
 .∊                   # And mirror the entire string vertically with overlap
                      # (after which the result is output implicitly)

내이 05AB1E 팁을 참조하십시오 (섹션 얼마나 큰 정수를 압축하는 방법을? ) 이유를 이해하는 ŽüÎ것입니다 64210.

3 JonathanAllan Sep 08 2020 at 01:41

젤리 , 52 바이트

³L>9ȯ
L11_»2⁶ẋŒHṚjµL_⁽|hḤD©Ḥ¤⁶ẋ;W¬1¦Ø0j0ç?Ɱ⁶ẋ®¤;"ŒḄY

결과를 인쇄하는 전체 프로그램.

온라인으로 시도하십시오!

어떻게?

³L>9ȯ - Link 1: unused argument; list of characters, Y
³     - program argument, the given text (same as T in the main Link)
 L    - length
  >9  - greater than nine?
    ȯ - logical OR with Y
 
L11_»2⁶ẋŒHṚjµL_⁽|hḤD©Ḥ¤⁶ẋ;W¬1¦Ø0j0ç?Ɱ⁶ẋ®¤;"ŒḄY - Main Link: list of characters, T
L                                              - length
 11_                                           - 11 - that
    »2                                         - max of that and two
      ⁶ẋ                                       - that many spaces
        ŒH                                     - split in two
          Ṛ                                    - reverse (get longer part on the right)
           j                                   - join with T
            µ                                  - start a new monadic chain - f(X=that)
                      ¤                        - nilad followed by link(s) as a nilad:
               ⁽|h                             -   32105
                  Ḥ                            -   double -> 64210
                   D                           -   digits -> [6,4,2,1,0]
                    ©                          -   store in register
                     Ḥ                         -   double -> [12,8,4,2,0]
             L_                                - length (X) minus that (vectorises)
                       ⁶ẋ                      - that many spaces (vectorises)
                          W                    - wrap X in a list
                         ;                     - concatenate
                           ¬1¦                 - logical NOT first line
                                                   (changing spaces to 0s)
                              Ø0               - [0,0]
                                    Ɱ          - map across the lines with:
                                   ?           -   if...
                                  ç            -   ...condition: call Link 1 f([0,0], line)
                                j              -   ...then: ([0,0]) join with (line)
                                 0             -   ...else a single zero
                                        ¤      - nilad followed by link(s) as a nilad:
                                     ⁶         -   space
                                       ®       -   recall from register -> [6,4,2,1,0]
                                      ẋ        -   repeat (vectorises)
                                         ;"    - zip with concatenation
                                                   (prefix lines with spaces)
                                           ŒḄ  - bounce (reflect top lines to the bottom)
                                             Y - join with newlines
                                               - implicit print
3 Jitse Sep 08 2020 at 19:36

Python 3 , 134 바이트

lambda s:'\n'.join(f'{0:{i}}{0**i*s:{"0 "[i<6]}^{max(i*2,len(s)+4,13)-(i*2or 2)}}'+'0'[i+i>10>len(s):]for i in(7,5,3,2,1,0,1,2,3,5,7))

온라인으로 시도하십시오!

2 KjetilS. Sep 07 2020 at 22:58

Perl 5 , 155 바이트

sub f{$_=pop;substr$r=64210001246=~s,.,$"x$&.($&-6?0 .$"x(11-$&*2).0:0).$/,ger=~s,^.{6}(.),($l=y|||c-9)>0?$&.$1x$l:$&,mger,$l>0?59+5*$l:59-$l/2,$l+9,$_;$r}

온라인으로 시도하십시오!

약간 풀림 :

sub f{
  $_=pop;                           # $_ = input text substr # args: string, offset, length, replacement $r=                             # $r = result string init to empty rectangle 64210001246 # digits are spaces before first 0 each line =~s,.,$"x$&.($&-6?0 .$"x(11-$&*2).0:0).$/,ger =~s,^.{6}(.),($l=y|||c-9)>0?$&.$1x$l:$&,mger,
    $l>0 ? 59+5*$l : 59-$l/2, # insert input text at this position $l+9,                           # ...this length ($l=input length minus 9) $_;                             # replacement = input
  $r                                # return result
}