Espandi un numero


23

Questa sfida si basa su questa domanda StackOverflow .

Con un numero positivo come input, emettilo come somma di ogni cifra moltiplicata per la sua rappresentazione power-of-10.

Ingresso

Un numero, come un numero intero, una stringa o un elenco di cifre / caratteri.

  • Il numero sarà strettamente positivo.
  • Se si accetta il numero come stringa o elenco, non inizierà con a 0.

Produzione

Una stringa che rappresenta una somma di ciascuna cifra base-10 rilevante, ognuna moltiplicata per la rispettiva potenza base-10. Una somma è rappresentata come a + b. +Se lo desideri, puoi utilizzare fino a uno spazio attorno a ciascun lato del segno. Gli operandi sono elencati in ordine decrescente.

  • 0 non può mai essere un operando valido.
  • Il +segno (circondato o meno da spazi) potrebbe non essere la parte iniziale o finale.

Esempi

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

Uscite non valide

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

Questo è code-golf quindi vince il codice più corto in byte!




Possiamo emettere la somma al contrario? Ex. 123 = 3 + 20 + 100
Quintec

1
sono consentiti spazi iniziali e finali?
ngn,

2
Qual è l'output previsto per l'ingresso 0? (Se 0 è un input non valido in primo luogo, quindi dovrebbe essere rimosso dagli esempi di output non validi IMO)
Pedro A

Risposte:


11

Python 3: 83 80 79 byte

Provalo online!

La mia prima presentazione su Code Golf.

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

-3 byte per ovs. Grazie per quel suggerimento utile :) -4 byte di mypetlion. Grazie per quel suggerimento di accorciamento :)


Benvenuti in PPCG! Puoi migliorare il tuo punteggio riordinando la tua istruzione if in if'0'<t[i]e cambiando la tua formula da x-i-1a x+~i. Ecco un link TIO con modifiche passo dopo passo.
Ovs,

Modificare l' printistruzione in print(*[t[i]+'0'*(x+~i)for i in range(x)if'0'<t[i]],sep='+')per salvare 1 byte.
mypetlion,

10

Gelatina , 9 byte

ḊƬḌQIAj”+

Provalo online!

Come funziona

ḊƬḌ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
Approccio intelligente!
Quintec,

8

JavaScript (ES6), 47 byte

Accetta l'input come numero intero.

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

Provalo online!

Commentate

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 byte

Supponendo che gli interi siano tutti inferiori a 1e10, che è comunque maggiore dell'intero massimo a 32 bit ...

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

Provalo online!


Bene, 10^(nchar(n):1-1teoricamente funzionerebbe per qualsiasi numero intero ...
Giuseppe,

1
Sarebbe, ma guarda tutti quei byte extra!
J.Doe,

7

Shakespeare Programming Language , 807 806 805 804 byte

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

Provalo online!

-23 byte se un carattere null può essere emesso per primo

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

Spiegazione

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

Gelatina ,  12  11 byte

J’⁵*Ṛ×ḟ0j”+

Un programma completo che accetta il numero come un elenco di cifre (in formato Python) che stampa il risultato.

Provalo online!

Come?

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"

Precedente @ 12 byte:

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

5

Haskell, 60 54 byte

Modifica: -6 byte grazie a Delfad0r.

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

Prende il numero di input come stringa.

Provalo online!

    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'<$)).(:))""salva 6 byte Provalo online! .
Delfad0r

1
@ Delfad0r: bello, grazie mille!
nimi,

4

05AB1E , 10 byte

Implementazione diretta.
Immettere come elenco di cifre.

āR<°*0K'+ý

Provalo online!

Spiegazione

    *        # multiply each digits in the input with
āR<°         # 10^(len(input)-1-index)
     0K      # remove results that are zero
       '+ý   # merge on "+"

4

Python 2 , 64 byte

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

Una funzione senza nome che accetta un elenco di cifre ne restituisce una stringa.

Provalo online!

enumerate(n)produrrebbe tuple di index, itemacross ncon un indice a partire da 0.

Tuttavia enumerateprende inoltre un indice iniziale opzionale come secondo argomento, impostando questo -len(n)otteniamo indici ( es) di -len(n), -len(n)+1..., -1.

Questo significa che il numero di zeri finali richieste per qualsiasi elemento ( b) è -1-e, che viene ~equindi ~e*'0'ottiene i zeri finali richieste.

`b`ottiene una rappresentazione in forma di stringa della cifra intera be la +concatena con quegli zeri.

if bfiltra le voci con b==0.

'+'.join(...)quindi unisce le stringhe risultanti con +caratteri.


4

Python 2, 82 73 71 byte

-9 byte grazie a @ovs

-2 byte grazie a @JonathanAllan

lambda n:'+'.join(v+'0'*(len(`n`)-i)for i,v in enumerate(`n`,1)if'0'<v)

Provalo online


4

Haskell , 56 55 52 byte

-4 byte grazie a nimi .

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

Provalo online!


spiegazione

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 "" = ""

Provalo online!


3

Perl 6 , 38 byte

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

Provalo online!

Blocco di codice anonimo che accetta un elenco di cifre e restituisce una stringa.

Spiegazione:

{                                    }  # 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 byte

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

-5 byte grazie a @dzaima

Prefisso anonimo. Accetta l'input come stringa. TIO

(Questa è la prima volta che utilizzo APL su PPCG, probabilmente golfabile. Inoltre, maledetto, zero!)


41 byte con⎕IO←0
dzaima,

3

Retina , 19 byte

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

Provalo online! Il link include casi di test. Spiegazione:

L`[1-9]

Elenca tutte le cifre diverse da zero

$
$&$.'*0

Per ogni cifra, aggiungi tutti gli zeri quante erano le cifre finali.

|'+

Separare ogni risultato con +s anziché la nuova riga predefinita.

Retina 0.8.2 , 21 byte

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

Provalo online! Il link include casi di test. Spiegazione:

M&!`[1-9].*

Elencare tutti i suffissi dell'input che iniziano con cifre diverse da zero.

\B.
0

Sostituisci tutte le cifre finali con zeri.

¶
+

Unisci i risultati con +s.


3

C (gcc) , 71 69 byte

Ogni passaggio della funzione ricorsiva sottrae la parte che verrà stampata e passa il resto del numero.

Grazie a ceilingcat per il suggerimento.

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

Provalo online!


3

Brachylog , 35 32 byte

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

-3 byte perché 0 non è un input valido

Provalo online! o testuite

Spiegazione

                                    #   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"

L'OP ha ora specificato che 0 non è un input che devi gestire, quindi puoi rimuoverlo |∧Ṡdalla fine. :)
DLosc,

3

Brachylog v2, 15 byte

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

Provalo online!

Molto, molto inefficiente.

In qualche modo, questo riesce a usare solo 6 byte su ciò che nella maggior parte delle lingue è la parte difficile (suddividendo il numero nella forma a 10 b dove un è una singola cifra, in ordine decrescente) e un intero 9 byte per "unisci con +"(che è incorporato nella maggior parte delle lingue del golf, ma non di Brachylog).

A differenza della maggior parte dei miei invii di Brachylog (che sono funzioni), questo è un programma completo, che prende input da input standard e produce output su output standard.

Spiegazione

~+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.

(Il motivo wᵐè usato piuttosto che il più normale cè che abbiamo a che fare con un elenco eterogeneo - contiene sia numeri che stringhe - e piuttosto che consentire a questi di mescolarsi, è più semplice stamparli tutti singolarmente.)

L'algoritmo qui forza bruta su tutte le partizioni additive dell'input fino a quando non ne trova una adatta (!). Brachylog preferisce il partizionamento in meno possibilità e con le possibilità ordinate in ordine crescente, quindi la prima soluzione che troverà è il contrario della soluzione che la domanda sta ponendo. Quindi non ci resta che invertirlo per ottenere la soluzione che vogliamo.


2

Pulito , 73 byte

import StdEnv,Text
$n=join"+"[rpad{c}(size n-p)'0'\\c<-:n&p<-[0..]|c>'0']

Provalo online!

Definisce la funzione che $ :: String -> Stringaccetta una stringa e restituisce una stringa.



2

Attache , 37 byte

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

Provalo online!

Versione senza punti (41 byte): Join&"+"##`\&:Id##`-&>Pairs@`'&0@Suffixes

Spiegazione

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

Powershell, 55 52 byte

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

Lo script prevede una matrice di stringhe, ogni stringa contiene una cifra. Script di prova:

$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"
}

Produzione:

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

2

Japt , 13 byte

Accetta input come una matrice di cifre.

í*¡ApYÃw)f q+

Provalo


Spiegazione

í                 :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 "+"

Alternativa

Accetta l'input come una matrice di stringhe di cifre.

ËúTUÊ-EÃfn q+

Provalo


2

Java 10, 82 78 byte

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;}

La risposta JavaScript di Port of Arnauld (ES6) .
-2 byte grazie a @ceilingcat .
-2 byte grazie ad Arnauld .

Provalo online.

Spiegazione:

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`

Suppongo che questa risposta sarebbe valida anche per la domanda originale . :) (Forse con n%massegnato a una variabile per la leggibilità.)
Arnauld


1
@ceilingcat In realtà, m<ndovrebbe funzionare.
Arnauld,

2

SNOBOL4 (CSNOBOL4) , 134 133 129 byte

	N =INPUT
	S =SIZE(N) - 1
V	N LEN(X) LEN(1) . V	:F(O)
	O =GT(V) O V DUPL(0,S - X) '+'
	X =X + 1	:(V)
O	O ARB . OUTPUT RPOS(1)
END

Provalo online!

Hai salvato un intero byte eseguendo l'elaborazione delle stringhe anziché l'aritmetica!


2

sed -E ,109 99 97 75 74 byte

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

Ogni riga dell'input è considerata un numero separato. Provalo online .

Spiegazione:

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

... posso giocare ancora a golf, presumo.


Ciao e benvenuto in PPCG. La tua risposta sembra buona, anche se non capisco perché hai aggiunto un caso di test BADC0FFEE . Penso che la sfida riguardi solo le rappresentazioni decimali.
Jonathan Frech,

Non è necessario gestire 01010101010o 000000, secondo le specifiche della sfida. Questo salva qualche byte?
Dennis,

@Dennis Molto probabilmente no, poiché gli zeri iniziali e quelli intermedi si comportano allo stesso modo, quindi devo comunque cancellarli.
hidefromkgb,

2

Brainfuck, 147 byte

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

Provalo online! (Dovrai spuntare la casella "!" E digitare il tuo input dopo il "!" Sulla seconda riga del codice, altrimenti continuerà a chiedere input per sempre.)

Probabilmente non sarà la risposta più breve o il più breve possibile, ma è stato abbastanza divertente provare a farlo in Brainfuck, quindi potrei anche pubblicarlo.

Come sottolineato da @JoKing, questo programma non rimuove gli 0. Proverò a risolvere questo problema, ma potrebbe essere piuttosto difficile.

Spiegazione:

>>+[[<]>+[>],]                            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

Siamo spiacenti, ma questo non rimuove gli zeri come specificato. Provalo online!
Jo King,

Grazie, non me ne sono accorto. Proverò a risolverlo. Mentre lo sono, modificherò il mio post
FinW,

2

APL (Dyalog Unicode) , 20 byte

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

Provalo online!

Accetta input come vettore di cifre. Emette uno spazio prima e dopo ciascuno +e include una quantità variabile di spazi iniziali.

Questo è un treno È diviso nel seguente.

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

La prima funzione è , questo inverte l'array, quindi 1 0 2diventa 2 0 1.

Quindi entriamo in (10×⊢)\, che viene applicato alla matrice invertita. Questa parte è ispirata dalla risposta di ngn alla sfida Boustrophedonise. Prendendo in prestito la spiegazione di ngn, dato un vettore di cifre A B C ..., l'applicazione (10×⊢)\su questo vettore fornisce quanto segue.

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

On 2 0 1, (10×⊢)\2 0 100.

Il prossimo arriva 0~⍨. Questo rimuove tutte le 0s dall'array, dando 2 100.

Finalmente arriva la +s. {⍵'+'⍺}/è una riduzione che parte da destra che concatena l'arg sinistro con un +, seguito dall'arg destro. In effetti, questo inverte l'array mentre si inseriscono +s. Questo dà 100 '+' 2, che viene visualizzato come 100 + 2.


2

MathGolf , 12 11 10 byte

hrzúm*ç'+u

Provalo online!

Spiegazione

Il primo comando non è necessario in quanto l'input può essere fornito come un elenco di cifre.

(▒           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

Potrei aggiungere un operatore di moltiplicazione a coppie di un byte, ma che attualmente non fa parte del linguaggio. Quindi ho potuto rimuovere un byte da questa soluzione.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.