숫자를 확장하십시오


23

이 과제는 이 Stackoverflow 질문을 기반으로 합니다 .

양수를 입력으로하여 10의 거듭 제곱으로 곱한 각 자릿수의 합계로 출력하십시오.

입력

정수, 문자열 또는 숫자 / 문자 목록으로 표시되는 숫자입니다.

  • 숫자는 양수입니다.
  • 숫자를 문자열 또는 목록으로 승인하면 숫자로 시작하지 않습니다 0.

산출

각각의 관련 10 진 숫자의 합을 나타내는 문자열로, 각각의 10 진수 거듭 제곱이 곱해집니다. 합은로 표시됩니다 a + b. +원하는 경우 부호의 양쪽에 최대 하나의 공간을 사용할 수 있습니다 . 피연산자는 내림차순으로 나열됩니다.

  • 0 유효한 피연산자가 될 수 없습니다.
  • +기호 (또는 스페이스로 둘러싸인 생략) 선행 또는 후행 일부가 될 수 없다.

Input       Output
12          10 + 2
         or 10+2
         or 10 +2
         or 10+ 2
9           9
123         100 + 20 + 3
10          10
101         100 + 1

유효하지 않은 출력

2           1 + 1
10          10 + 0
1           0 + 1
12          + 10 + 2
12          10 + 2 +
12          2 + 10

이것은 코드 골프이므로 바이트 단위의 가장 짧은 코드가 이깁니다!




합을 역으로 출력 할 수 있습니까? 전의. 123 = 3 + 20 + 100
Quintec

1
선행 및 후행 공백이 허용됩니까?
ngn

2
입력 0에 대한 예상 출력은 무엇입니까? (처음에 0이 유효하지 않은 입력 인 경우 유효하지 않은 출력 예 IMO에서 제거해야합니다.)
Pedro A

답변:


11

파이썬 3:83 80 79 바이트

온라인으로 사용해보십시오!

내 첫 번째 코드 골프 제출.

t=input();x=len(t);print(*[t[i]+'0'*(x+~i)for i in range(x)if'0'<t[i]],sep='+')

ovs -3 바이트 유용한 팁을 주셔서 감사합니다 :) mypetlion의 -4 바이트. 단축 팁 주셔서 감사합니다 :)


PPCG에 오신 것을 환영합니다! if 문을 재정렬 if'0'<t[i]하고 공식을에서 x-i-1로 변경하여 점수를 향상시킬 수 있습니다 x+~i. 다음 은 단계별 변경 사항이 포함 된 TIO 링크입니다.
ovs

1 바이트를 저장 하도록 print명령문을 변경하십시오 print(*[t[i]+'0'*(x+~i)for i in range(x)if'0'<t[i]],sep='+').
mypetlion

10

젤리 , 9 바이트

ḊƬḌQIAj”+

온라인으로 사용해보십시오!

작동 원리

ḊƬḌQIAj”+  Main link. Argument: A (digit array)

 Ƭ         Til; apply the link to the left until the results are no longer unique.
           Return all unique results.
Ḋ              Dequeue; discard the first element.
           For input [1,2,0,4], this yields [[1,2,0,4], [2,0,4], [0,4], [4], []].
  Ḍ        Undecimal; convert the digit arrays into integers.
           For input [1,2,0,4], this yields [1204, 204, 4, 4, 0].
   Q       Unique; deduplicate the resulting integers.
           For input [1,2,0,4], this yields [1204, 204, 4, 0].
    I      Increments; yield the forward differences.
           For input [1,2,0,4], this yields [-1000, -200, -4].
     A     Absolute value.
      j”+  Join with separator '+'.

3
똑똑한 접근!
Quintec

8

자바 스크립트 (ES6), 47 바이트

입력을 정수로 취합니다.

f=(n,m=1,k=n%m)=>n-k?f(n-k,m*10)+(k?'+'+k:''):n

온라인으로 사용해보십시오!

댓글

f = (                     // f is a recursive function taking:
  n,                      //   n = number to process
  m = 1,                  //   m = modulo (a power of 10, starting at 1)
  k = n % m               //   k = n mod m
) =>                      //
  n - k ?                 // if n is not equal to k:
    f(n - k, m * 10)      //   do a recursive call with n - k and m * 10
    + (k ? '+' + k : '')  //   if k is not zero: append '+' and k
  :                       // else:
    n                     //   append n and stop recursion

7

R , 55 바이트

정수가 모두 1e10 미만이라고 가정하면 어쨌든 최대 32 비트 정수보다 큽니다 ...

function(n,p=10^(9:0),x=p*n%/%p%%10)cat(x[!!x],sep='+')

온라인으로 사용해보십시오!


글쎄, 10^(nchar(n):1-1이론적으로 모든 정수에 대해 작동합니다 ...
Giuseppe

1
그것은하지만 여분의 모든 바이트를보십시오!
J.Doe

7

셰익스피어 언어 프로그래밍 , 807 806 805 804 바이트를

,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy!Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.You be I.Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.[Exit Ford][Enter Page]Ajax:Be you nicer zero?If sospeak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]Ajax:Open heart.Remember I.You zero.Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.Scene C:.Ajax:Recall.Ford:You be I.Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.

온라인으로 사용해보십시오!

널 문자가 먼저 출력 될 수있는 경우 -23 바이트

,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy!Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.You be I.Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.[Exit Ford][Enter Page]Ajax:Speak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]Ajax:Open heart.Remember me.You zero.Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.Scene C:.Ajax:Recall.Ford:You be I.Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.

설명

,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]

    Boilerplate, introducing the characters.

Ford:Listen tothy!

    Input a value to Ajax.

Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.

    Push the digits of Ajax onto Ford's stack, and set Ford's value to be the number of digits in Ajax.

You be I.

    Store the number of digits in the input to Ajax.

Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.

    Pop the next digit off the stack, and skip processing it if it equals 0.

[Exit Ford][Enter Page]Ajax:Be you nicer zero?If sospeak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]

    All characters start out with a value of 0.
    If Page is 0, that means this is the first number being processed, and we shouldn't output a plus.
    In either case, store the ASCII value of "+" to Page to output next time it is needed.

Ajax:Open heart.Remember I.You zero.

    Output the digit, save the remaining-digit-count for later, and store 0 to Ford for output purposes.

Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.

    Output one fewer 0 than the number of remaining digits to process.

Scene C:.Ajax:Recall.Ford:You be I.

    Store the remaining-digit-count back into Ajax.

Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.

    Subtract 1 from the remaining-digit-count, and loop back until there are no more digits left to process.


6

젤리 ,  12  11 바이트

J’⁵*Ṛ×ḟ0j”+

숫자를 숫자 목록 (파이썬 형식)으로 받아 들여 결과를 인쇄하는 전체 프로그램.

온라인으로 사용해보십시오!

방법?

J’⁵*Ṛ×ḟ0j”+ - Main Link: list of digits  e.g. [1,0,2,0,3,0]
J           - range of length                 [1,2,3,4,5,6]
 ’          - decrement (vectorises)          [0,1,2,3,4,5]
  ⁵         - literal 10                      10
   *        - exponentiate (vectorises)       [1,10,100,1000,10000,100000]
    Ṛ       - reverse                         [100000,10000,1000,100,10,1]
     ×      - multiply (vectorises)           [100000,0,2000,0,30,0]
      ḟ0    - filter discard zeros            [100000,2000,30]
        j”+ - join with '+'                   [100000,'+',2000,'+',30]
            - implicit (smashing) print       "100000+2000+30"

이전 @ 12 바이트 :

Ḣ;0€ƊÐƤẸƇj”+

5

하스켈, 60 54 바이트

편집 : Delfad0r 덕분에 -6 바이트.

tail.(>>=('+':)).filter(>="1").scanr((.('0'<$)).(:))""

입력 번호를 문자열로 사용합니다.

온라인으로 사용해보십시오!

    scanr(        )""    -- starting with the empty string fold from the right and
                         -- collect the intermediate results in a list
      (.('0'<$)).(:)     -- non pointfree: \d s -> d : ('0'<$s)
                         -- i.e. take the next digit 'd' and append the current result
                         -- from the scanr where each char is replaced by 0
                         --
                         -- e.g. "103" -> ["100","00","3"]
                         --
  f ilter(>="1")         -- keep only elements that have not a 0 as the first char
 (>>=('+':))             -- prepend a + to each element and flatten into
                         -- a single list
tail                     -- drop the first char, ie.e the leading +

2
tail.(>>=('+':)).filter(>="1").scanr((.('0'<$)).(:))""6 바이트 절약 온라인으로 사용해보십시오! .
Delfad0r

1
@ Delfad0r : 감사합니다, 고마워요!
nimi


4

파이썬 2 , 64 바이트

lambda n:'+'.join(`b`+~e*'0'for e,b in enumerate(n,-len(n))if b)

숫자 목록을 가져 와서 n문자열을 반환 하는 명명되지 않은 함수입니다 .

온라인으로 사용해보십시오!

enumerate(n)의 튜플 얻을 것이다 index, item전역을 n인덱스에서 시작하여 0.

그러나 enumerate에이 설정하여, 두 번째 인수로 옵션 시작 인덱스를 가져 오며 -len(n)우리가 인덱스 (수 e의들) -len(n), -len(n)+1, ..., -1.

이 수단 모든 항목에 필요한 후행 0의 수는 ( b)입니다 -1-e되는, ~e그래서 ~e*'0'필요한 후행 0을 가져옵니다.

`b`정수 숫자의 문자열 표현을 가져옵니다 b+그 제로에 이것을 연결합니다.

if b로 항목을 필터링합니다 b==0.

'+'.join(...)그런 다음 결과 문자열을 +문자 와 결합합니다 .



4

하스켈 , 56 55 52 바이트

nimi 덕분에 -4 바이트 .

tail.f
f('0':x)=f x
f(d:x)='+':d:('0'<$x)++f x
f x=x

온라인으로 사용해보십시오!


설명

g :: String -> String

-- drop the first char (the leading +) from f
g = tail.f

f :: String -> String

-- if the first digit is 0, continue with the rest of the number
f ( '0' :rest) = f rest

-- otherwise, add a +, the digit and as many 0s as there are digit in the rest.
f (digit:rest) = '+' : digit : ('0' <$ rest) ++ f rest

-- if there is no digit left, return the empty string
f "" = ""

온라인으로 사용해보십시오!


3

펄 6 , 38 바이트

{join '+',grep +*,($_ Z~[R,] 0 Xx^$_)}

온라인으로 사용해보십시오!

숫자 목록을 가져 와서 문자열을 반환하는 익명 코드 블록.

설명:

{                                    }  # Anonymous code block
                   $_ Z~   # Zip concatenate the list of digits with
                        [R,] 0 Xx^$_   # The correct number of 0s

          grep +*,(                 )  # Filter out all all the 0 values
 join '+',   # And join with '+'s

3

APL (Dyalog), 46 41 40 바이트

{¯1↓∊{'0'=⊃⍵:⍬⋄⍵}¨⍵,¨('0'⍴⍨¨⌽⍳≢⍵),¨'+'}

@dzaima 덕분에 -5 바이트

익명 접두사 기능. 입력을 문자열로받습니다. TIO

(PPCG에서 APL을 사용한 것은 이번이 처음입니다. 아마 골프를 타실 수도 있습니다. 또한 저주를 제로로 만드십시오!)


41 바이트⎕IO←0
dzaima

3

레티 나 , 19 바이트

|'+L$`[1-9]
$&$.'*0

온라인으로 사용해보십시오! 링크에는 테스트 사례가 포함됩니다. 설명:

L`[1-9]

0이 아닌 모든 숫자 나열

$
$&$.'*0

각 숫자에 대해 후행 숫자가있는만큼 0을 추가하십시오.

|'+

각 결과를 +기본 줄 바꿈 대신 s로 구분 하십시오.

레티 나 0.8.2 , 21 바이트

M&!`[1-9].*
\B.
0
¶
+

온라인으로 사용해보십시오! 링크에는 테스트 사례가 포함됩니다. 설명:

M&!`[1-9].*

0이 아닌 숫자로 시작하는 입력의 모든 접미사를 나열하십시오.

\B.
0

모든 후행 숫자를 0으로 바꾸십시오.

¶
+

+s로 결과를 결합하십시오 .


3

C (gcc) , 71 69 바이트

재귀 함수의 각 단계는 인쇄 할 부분을 빼고 나머지 숫자를 전달합니다.

제안에 대한 천장 고양이 덕분에.

g(v,c,w){v&&printf("+%d"+!g(v-w,c*10)+!w*3,w=v%c);w=v;}f(v){g(v,10);}

온라인으로 사용해보십시오!


3

Brachylog , 35 32 바이트

l⟧₅;?z{tℕ₁I&h;10↔^;I×ṫ}ˢ;"+"zckc

-3 바이트는 0이 유효한 입력이 아닙니다.

온라인으로 사용해보십시오! 또는 테스트 슈트

설명

                                    #   implicit input          eg  105
l                                   #   length of input             3
 ⟧₅                                 #   descending range ]n,0]      [2, 1, 0]
   ;?                               #   pair with input             [[2, 1, 0], [105]]
     z                              #   zip (considers numbers as array of digits)
                                    #                               [[2, 1], [1, 0], [0, 5]]
      {               }ˢ            #   select (map and filter)     [2, 1]  |   [1, 0]  |   [0, 5]
       t                            #       tail (last element)     1       |   0       |   5
        ℕ₁                          #       is at least 1           1       |   fail    |   5
          I                         #       store in I
           &h                       #       head of input           2       |           |   0
             ;10↔                   #       pair with 10 & reverse  [10, 2] |           |   [10, 0]
                 ^                  #       power                   100     |           |   1
                  ;I                #       pair with I             [100, 1]|           |   [1, 5]
                    ×               #       multiply                100     |           |   5
                     ṫ              #       to string               "100"   |           |   "5"
                        ;"+"        #   pair with "+"               [["100", "5"], "+"]
                            z       #   zip (cycles shorter)        [["100", "+"], ["5", "+"]]
                             c      #   concat (flattens)           ["100", "+", "5", "+"]
                              k     #   knife (remove last)         ["100", "+", "5"]
                               c    #   concat                      "100+5"

OP는 이제 0이 처리해야하는 입력이 아니라고 지정 |∧Ṡ하여 끝에서를 제거 할 수 있습니다 . :)
DLosc

3

Brachylog v2, 15 바이트

~+bᵛ⁰↔;"+"zckwᵐ

온라인으로 사용해보십시오!

매우 비효율적입니다.

어떻게 든,이 (양식에 분할 수 대부분의 언어에 어려운 부분이 무엇인지 만 6 바이트를 사용하는 관리 10 (B) A는 은 "에 조인 한 자리가 내림차순입니다), 그리고 전체 9 바이트를 "(대부분의 골프 언어에 내장되어 있지만 브라 키로그는 아님).+

대부분의 Brachylog 제출 (함수)과는 달리이 프로그램은 표준 입력에서 입력을 받아 표준 출력에서 ​​출력을 생성하는 전체 프로그램입니다.

설명

~+bᵛ⁰↔;"+"zckwᵐ
~+               Find an additive partition of the input number
   ᵛ               such that each component of the partition,
  b                when the first digit is removed
    ⁰              is equal to 0;
     ↔           reverse it,
      ;"+"z      pair every element with "+",
           c     flatten the resulting list one level,
            k    remove the last element (i.e. the final "+"),
             w   and print
              ᵐ  each remaining element.

( 우리가 이질적인 목록을 다루는 이유 wᵐc숫자와 문자열이 모두 포함되어 있기 때문입니다. 숫자와 문자열이 모두 포함되어 있기 때문에 이들을 혼합하지 않고 모두 개별적으로 인쇄하는 것이 가장 간단합니다.)

여기서 알고리즘은 입력의 모든 추가 파티션에 대해 적절한 입력 (!)을 찾을 때까지 무차별 강제 실행합니다. Brachylog는 더 적은 가능성으로 나누고 가능성은 오름차순으로 정렬하는 것을 선호하므로 가장 먼저 찾은 해결책은 질문이 요구하는 해결책의 반대입니다. 따라서 원하는 솔루션을 얻으려면 그것을 뒤집어 야합니다.




2

첨부 , 37 바이트

Join&"+"@{Id\`-&>Pairs[_'0]}@Suffixes

온라인으로 사용해보십시오!

포인트 프리 버전 (41 바이트) : Join&"+"##`\&:Id##`-&>Pairs@`'&0@Suffixes

설명

Join&"+"@{Id\`-&>Pairs[_'0]}@Suffixes      input e.g.: 1203
                             Suffixes      take the suffixes of the input digit
                                           e.g.: [1203, 203, 3, 3] 
         {                 }@              apply the inner lambda to the suffixes:
                       _'0                   append `0`
                                             e.g.: [1203, 203, 3, 3, 0]
                 Pairs[   ]                  generate the pairs of integers of the above
                                             e.g.: [[1203, 203], [203, 3], [3, 3], [3, 0]]
             `-&>                            subtraction over each pair
                                             e.g.: [1000, 200, 0, 3]
          Id\                                keep only truthy (nonzero) elements
                                             e.g.: [1000, 200, 3]
Join&"+"@                                  join the result by `+`
                                           e.g.: "1000+200+3"


2

파워 쉘, 55 52 바이트

$i=$args.Count;($args|%{$_+'0'*--$i}|?{+$_})-join'+'

스크립트는 문자열 배열을 예상하며 각 문자열에는 한 자리수가 포함됩니다. 테스트 스크립트 :

$f = {

$i=$args.Count;($args|%{$_+'0'*--$i}|?{+$_})-join'+'

}

@(
    ,('10','1','0')
    ,('10+2','1','2')
    ,('9','9')
    ,('100+20+3','1','2','3')
    ,('100+1','1','0','1')
) | % {
    $e, $a = $_
    $r = &$f @a
    "$($e-eq$r): $(-join$a)=$r"
}

산출:

True: 10=10
True: 12=10+2
True: 9=9
True: 123=100+20+3
True: 101=100+1

2

Japt , 13 바이트

숫자 배열로 입력을받습니다.

í*¡ApYÃw)f q+

시도 해봐


설명

í                 :Interleave
  ¡               :  Map input
   A              :    10
    p             :    To the power of
     Y            :    The current 0-based index
      Ã           :  End map
       w          :  Reverse
 *                :  Reduce each pair by multiplication
        )         :End interleaving
         f        :Filter (remove 0s)
           q+     :Join with "+"

대안

숫자 문자열 배열로 입력을받습니다.

ËúTUÊ-EÃfn q+

시도 해봐


2

자바 10, 82 78 바이트

n->f(n,1)Object f(int n,int m){return m<n?f(n-n%m,m*10)+(n%m>0?"+"+n%m:""):n;}

포트 Arnauld 의 자바 스크립트 (ES6) 답 . @ceilingcat
덕분에 -2 바이트 . Arnauld 덕분에 -2 바이트 .

온라인으로 사용해보십시오.

설명:

n->                      // Method with int parameter & Object return-type
  f(n,1)                 //  Call the recursive method with `n` and 1

Object f(int n,int m){   // Recursive method with 2 int parameters & Object return-type
  return m<n?            //  If `m` is smaller than `n`:
          f(n-n%m,m*10)  //   Do a recursive call with `n-n%m` and `m` multiplied by 10
          +(n%m>0?       //   And if `n` is not divisible by `m`:
            "+"          //    Append a "+"
            +n%m         //    As well as `n%m`
           :             //   Else:
            "")          //    Append nothing more
         :               //  Else:
          n;}            //   Simply return the input `n`

이 답변이 원래의 질문에 대한 올바른 답변이라고 생각합니다 . :) ( n%m가독성을 위해 변수에 할당 되었을 수도 있습니다.)
Arnauld

1
좋은! 내 원래 솔루션 은 91 바이트였습니다.
Olivier Grégoire

1
@ceilingcat 사실, m<n작동합니다.
Arnauld


2

sed -E ,109 99 97 75 74 바이트

h;s:.:0:g;G
:l;s:.(.*)\n(.)(.*)\+?(.*):\1\n\3+\4\2\1:;tl
s:\+0+::g;s:..?::

입력의 각 줄은 별도의 숫자로 간주됩니다. 온라인으로 사용해보십시오 .

설명:

h;                                           | copy the original string to the temporary buffer
  s:.:0:g;                                   | substitute all digits with zeroes
          G                                  | append the original string to the substituted one
                                             |
:l;                                          | main loop start
   s:.(.*)\n(.)(.*)\+?(.*):\1\n\3+\4\2\1:;   | cut the next digit from the number, append with zeroes and add to the back
                                          tl | loop if the substitution hasn`t converged yet
                                             |
s:\+0+::g;                                   | remove all zero terms
          s:..?::                            | remove \n and the first +, if any

… 골프를 더 할 수 있다고 생각합니다.


PPCG에 오신 것을 환영합니다. BADC0FFEE 테스트 사례 를 추가 한 이유를 이해하지 못하더라도 귀하의 답변은 괜찮습니다 . 나는 도전이 십진 표현에 관한 것이라고 생각합니다.
Jonathan Frech

당신은 처리 할 필요가 없습니다 01010101010또는 000000도전 사양에 따라. 바이트가 절약됩니까?
Dennis

@Dennis 선행 0과 그 사이의 0이 동일하게 작동하므로 어쨌든 지워야합니다.
hidefromkgb

2

Brainfuck, 147 바이트

>>+[[<]>+[>],]-[>+>+<<-----]>--->--------<<<[<]>---[[<+<+>>-]<[>+<-]>>.<<<[>>[>]>.<<[<]<-]>>[>]>>.<<<[<]>>>[<[-]>[<+>-]>]>[<+>-]>[<+>-]<<<<[<]>-]>.

온라인으로 사용해보십시오! ( "!"라고 표시된 상자를 선택하고 코드의 두 번째 줄에서 "!"뒤에 입력을 입력해야합니다. 그렇지 않으면 계속 입력을 요구합니다.)

아마도 가장 짧은 대답이 아니거나 가능한 한 가장 짧은 골프를 치지 않을 것입니다.하지만 Brainfuck에서 시도하고 수행하는 것은 꽤 재미 있었으므로 게시 할 수도 있습니다.

@JoKing이 지적 했듯이이 프로그램은 0을 제거하지 않습니다. 나는 이것을 시도하고 고칠 것이지만 꽤 어려울 수 있습니다.

설명:

>>+[[<]>+[>],]                            Takes inputs and records the amount of them
-[>+>+<<-----]>--->--------               Sets the next 2 cells to 48 (0) and 43 (plus)
<<<[<]>---                                Returns to the start and corrects the number of inputs
                                          Loop
[[<+<+>>-]<[>+<-]>>.                      Prints the first number
<<<[>>[>]>.<<[<]<-]                       Prints the correct number of 0's
>>[>]>>.                                  Prints plus
<<<[<]>                                   Returns to the first cell
>>[<[-]>[<+>-]>]>[<+>-]>[<+>-]<<<<[<]>-]  Removes the first number and shifts everything up by one to make the second number the first 
                                          Loops until on last number
>.                                        Prints last number

죄송하지만 지정된대로 0을 제거하지는 않습니다. 온라인으로 사용해보십시오!
조 왕

고마워요. 시도하고 고칠 것입니다. 내가있는 동안 내 게시물을 편집 할 것입니다
FinW

2

APL (Dyalog Unicode) , 20 바이트

{⍵'+'⍺}/0~⍨(10×⊢)\∘

온라인으로 사용해보십시오!

숫자로 구성된 벡터로 입력을받습니다. 각 앞뒤에 공백이 있고 출력되는 +양의 선행 공백이 포함됩니다.

기차입니다. 다음과 같이 나뉩니다.

  ┌───┴───┐
  /     ┌─┼──┐
┌─┘     0   
{⍵'+'⍺} ┌─┘ ┌┴┐
        ~   \ 
          ┌─┘
       ┌──┼─┐
       10 × 

첫 번째 함수는입니다 . 이것은 배열을 반대로하므로 1 0 2됩니다 2 0 1.

그런 다음 (10×⊢)\반전 배열에 적용되는로 들어갑니다 . 이 부분은 Boustrophedonise 챌린지에 대한 ngn의 답변 에서 영감을 얻었습니다 . 숫자의 벡터 주어진, NGN의 설명을 빌려 A B C ..., 적용(10×⊢)\ 하여이 벡터에 하면 다음이 제공됩니다.

A (A (10×⊢) B) (A (10×⊢) (B (10×⊢) C)) ...
A ((10×⊢) B) ((10×⊢) (10×C)) ...
A (10×B) (10×10×C) ...

2 0 1,(10×⊢)\ 제공합니다 2 0 100.

다음이 온다 0~⍨. 이것은 0배열에서 모든을 제거하고을 제공 2 100합니다.

마침내 +s 가 온다 . {⍵'+'⍺}/는 왼쪽 arg를 a로 연결하고 오른쪽 arg를 연결하는 오른쪽에서 시작하는 축소입니다 +. 효과적으로 +s 를 삽입하는 동안 배열을 반대로합니다 . 이것은 제공 100 '+' 2으로 표시되는, 100 + 2.


2

MathGolf , 12 11 10 바이트

hrzúm*ç'+u

온라인으로 사용해보십시오!

설명

입력을 숫자 목록으로 제공 할 수 있으므로 첫 번째 명령은 필요하지 않습니다.

(▒           Convert to a list of digits)
 h           Get length of input list without popping
  r          Push range(a)
   z         Reverse sort
    ú        Map i -> 10**i for each element in list
     m*      Element-wise multiplication
       ç     Filter faulty items in list
        '+   Push "+"
          u  Join with separator

1 바이트 인 페어 단위 곱셈 연산자를 추가 할 수 있지만 현재 언어의 일부는 아닙니다. 그런 다음이 솔루션에서 1 바이트를 제거 할 수 있습니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.