26
\$\begingroup\$

This challenge is based on this Stackoverflow question.

With a positive number as input, output it as the sum of each digit multiplied by its power-of-10 representation.

Input

A number, as an integer, a string or a list of digits/characters.

  • The number will be strictly positive.
  • If you accept the number as a string or list, it will not start with a 0.

Output

A string representing a sum of each relevant base-10 digits, each multiplied by its respective base-10 power. A sum is represented as a + b. You may use up to one space around each side of the + sign if you want. The operands are listed in descending order.

  • 0 can never be a valid operand.
  • The + sign (surrounded or not by spaces) may not be the leading or trailing part.

Examples

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

Invalid outputs

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

This is code-golf so the shortest code in bytes wins!

\$\endgroup\$
13
  • \$\begingroup\$ Sandbox \$\endgroup\$ Sep 9, 2018 at 8:13
  • \$\begingroup\$ Related \$\endgroup\$ Sep 9, 2018 at 12:32
  • \$\begingroup\$ Can we output the sum in reverse? Ex. 123 = 3+20+100 \$\endgroup\$
    – Quintec
    Sep 9, 2018 at 15:32
  • 1
    \$\begingroup\$ are leading and trailing spaces allowed? \$\endgroup\$
    – ngn
    Sep 9, 2018 at 21:10
  • 2
    \$\begingroup\$ What is the expected output for input 0? (If 0 is an invalid input in the first place, then it should be removed from the invalid output examples IMO) \$\endgroup\$
    – Pedro A
    Sep 10, 2018 at 11:55

42 Answers 42

11
\$\begingroup\$

Jelly, 9 bytes

ḊƬḌQIAj”+

Try it online!

How it works

ḊƬḌ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 '+'.
\$\endgroup\$
1
  • 4
    \$\begingroup\$ Smart approach! \$\endgroup\$
    – Quintec
    Sep 9, 2018 at 22:30
11
\$\begingroup\$

Python 3: 83 80 79 Bytes

Try It Online!

My first Code Golf submission.

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

-3 Bytes by ovs. Thank you for that useful tip :) -4 Bytes by mypetlion. Thank you for that shortening tip :)

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to PPCG! You can improve your score by reordering your if statement to if'0'<t[i] and change your formula from x-i-1 to x+~i. Here is a TIO link with step by by step changes. \$\endgroup\$
    – ovs
    Sep 9, 2018 at 9:04
  • \$\begingroup\$ Change the print statement to print(*[t[i]+'0'*(x+~i)for i in range(x)if'0'<t[i]],sep='+') to save 1 byte. \$\endgroup\$
    – mypetlion
    Sep 10, 2018 at 15:45
8
\$\begingroup\$

JavaScript (ES6), 47 bytes

Takes input as an integer.

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

Try it online!

Commented

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
\$\endgroup\$
0
7
\$\begingroup\$

R, 55 bytes

Assuming integers are all under 1e10, which is larger than the maximum 32 bit integer anyway...

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

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Well, 10^(nchar(n):1-1 would theoretically work for any integer... \$\endgroup\$
    – Giuseppe
    Sep 9, 2018 at 16:59
  • 1
    \$\begingroup\$ It would, but look at all those extra bytes! \$\endgroup\$
    – J.Doe
    Sep 9, 2018 at 16:59
7
\$\begingroup\$

Shakespeare Programming Language, 807 806 805 804 bytes

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

Try it online!

-23 bytes if a null character may be output first

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

Explanation

,.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.
\$\endgroup\$
6
\$\begingroup\$

Python 2, 64 bytes

f=lambda s='',*x:s and(s>'0')*(s+'0'*len(x)+(f(*x)and'+'))+f(*x)

Try it online!


Python 2, 66 bytes

f=lambda n,m=1:n>10and f(n/10,m*10)+(n%10>0)*('+'+`n%10*m`)or`n*m`

Try it online!

\$\endgroup\$
6
\$\begingroup\$

Jelly,  12  11 bytes

J’⁵*Ṛ×ḟ0j”+

A full program accepting the number as a list of digits (in Python format) which prints the result.

Try it online!

How?

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"

Previous @12 bytes:

Ḣ;0€ƊÐƤẸƇj”+
\$\endgroup\$
5
\$\begingroup\$

05AB1E, 10 bytes

Straight forward implementation.
Input as list of digits.

āR<°*0K'+ý

Try it online!

Explanation

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

Haskell, 60 54 bytes

Edit: -6 bytes thanks to Delfad0r.

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

Takes the input number as a string.

Try it 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 +
\$\endgroup\$
2
  • 2
    \$\begingroup\$ tail.(>>=('+':)).filter(>="1").scanr((.('0'<$)).(:))"" saves 6 bytes Try it online!. \$\endgroup\$
    – Delfad0r
    Sep 9, 2018 at 17:11
  • 1
    \$\begingroup\$ @Delfad0r: nice, thanks a lot! \$\endgroup\$
    – nimi
    Sep 9, 2018 at 20:27
4
\$\begingroup\$

Python 2, 64 bytes

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

An unnamed function which takes a list of digits, n, and returns a string.

Try it online!

enumerate(n) would yield tuples of index, item across n with an index starting at 0.

However enumerate also takes an optional starting index as its second argument, by setting this to -len(n) we get indices (es) of -len(n), -len(n)+1, ..., -1.

This means the number of required trailing zeros for any item (b) is -1-e, which is ~e so ~e*'0' gets the required trailing zeros.

`b` gets a string representation of the integer digit b and + concatenates this with those zeros.

if b filters out the entries with b==0.

'+'.join(...) then joins the resulting strings up with + characters.

\$\endgroup\$
4
\$\begingroup\$

Python 2, 82 73 71 bytes

-9 bytes thanks to @ovs

-2 bytes thanks to @JonathanAllan

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

Try it Online

\$\endgroup\$
0
4
\$\begingroup\$

Haskell, 56 55 52 bytes

-4 byte thanks to nimi.

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

Try it online!


explanation

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

Try it online!

\$\endgroup\$
0
3
\$\begingroup\$

Perl 6, 38 bytes

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

Try it online!

Anonymous code block that takes a list of digits and returns a string.

Explanation:

{                                    }  # 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
       
\$\endgroup\$
3
\$\begingroup\$

APL(Dyalog), 46 41 40 bytes

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

-5 bytes thanks to @dzaima

Anonymous prefix function. Takes input as a string. TIO

(This is my first time using APL on PPCG, probably golfable. Also, curse you, zeroes!)

\$\endgroup\$
1
  • \$\begingroup\$ 41 bytes with ⎕IO←0 \$\endgroup\$
    – dzaima
    Sep 9, 2018 at 20:48
3
\$\begingroup\$

Retina, 19 bytes

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

Try it online! Link includes test cases. Explanation:

L`[1-9]

List all non-zero digits

$
$&$.'*0

For each digit, append as many zeros as there were trailing digits.

|'+

Separate each result with +s instead of the default newline.

Retina 0.8.2, 21 bytes

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

Try it online! Link includes test cases. Explanation:

M&!`[1-9].*

List all suffixes of the input that begin with non-zero digits.

\B.
0

Replace all trailing digits with zeros.

¶
+

Join the results with +s.

\$\endgroup\$
3
\$\begingroup\$

C (gcc), 71 69 bytes

Each step of the recursive function subtracts the part that it will print and passes the rest of the number on.

Thanks to ceilingcat for the suggestion.

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

Try it online!

\$\endgroup\$
0
3
\$\begingroup\$

Brachylog, 35 32 bytes

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

-3 bytes cause 0 isn't a valid input

Try it online! or testsuite

Explanation

                                    #   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"
\$\endgroup\$
1
  • \$\begingroup\$ The OP has now specified that 0 is not an input you have to handle, so you can remove the |∧Ṡ from the end. :) \$\endgroup\$
    – DLosc
    Sep 11, 2018 at 15:55
3
\$\begingroup\$

Brachylog v2, 15 bytes

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

Try it online!

Very, very inefficient.

Somehow, this manages to use only 6 bytes on what is in most languages the hard part (splitting the number into the form a10b where a is a single digit, in descending order), and a whole 9 bytes for the "join with +" (which is a builtin in most golfing languages, but not Brachylog).

Unlike most of my Brachylog submissions (which are functions), this one's a full program, taking input from standard input and producing output on standard output.

Explanation

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

(The reason wᵐ is used rather than the more normal c is that we're dealing with a heterogenous list – it contains both numbers and strings – and rather than allowing these to mix, it's simplest to just print them all individually.)

The algorithm here brute-forces over all additive partitions of the input until it finds a suitable one (!). Brachylog favours partitioning into fewer possibilities, and with the possibilities sorted in ascending order, so the first solution it will find is the reverse of the solution that the question is asking for. So we just have to reverse it to get the solution we want.

\$\endgroup\$
3
\$\begingroup\$

Pip, 17 bytes

FI(REE,#a)*^aJ:'+

Attempt This Online!

Explanation

Different approach from my earlier 21-byte answer in Pip Classic:

FI(REE,#a)*^aJ:'+
      ,#a          Range(length(input number))
    EE             10 to the power of each element of the range
   R               Reversed
  (      )*        Multiply each element of that list by
           ^a      The corresponding element in split(input number)
FI                 Filter, removing zeros
             J:'+  Join on the + character

(A similar approach would be 19 bytes in Pip Classic: _FI(^a).RV0X,#aJ:'+.)

\$\endgroup\$
2
\$\begingroup\$

Clean, 73 bytes

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

Try it online!

Defines the function $ :: String -> String taking a string and returning a string.

\$\endgroup\$
2
\$\begingroup\$

Canvas, 14 13 bytes

A⁸L²-^×?²}]+*

Try it here!

\$\endgroup\$
2
\$\begingroup\$

Attache, 37 bytes

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

Try it online!

Pointfree version (41 bytes): Join&"+"##`\&:Id##`-&>Pairs@`'&0@Suffixes

Explanation

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"
\$\endgroup\$
2
\$\begingroup\$

C (gcc), 87 bytes

j;k;f(x){for(j=1;j<x;j*=10);for(;k=x*10/j*j/10%j,j/=10;)k&&printf("%d%c",k,j-1?43:10);}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Powershell, 55 52 bytes

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

Script expects an array of strings, each string contains one digit. Test script:

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

Output:

True: 10=10
True: 12=10+2
True: 9=9
True: 123=100+20+3
True: 101=100+1
\$\endgroup\$
2
\$\begingroup\$

Japt, 13 bytes

Takes input as an array of digits.

í*¡ApYÃw)f q+

Try it


Explanation

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

Alternative

Takes input as an array of digit strings.

ËúTUÊ-EÃfn q+

Try it

\$\endgroup\$
2
\$\begingroup\$

Java 10, 82 78 bytes

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

Port of Arnauld's JavaScript (ES6) answer.
-2 bytes thanks to @ceilingcat.
-2 bytes thanks to Arnauld.

Try it online.

Explanation:

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`
\$\endgroup\$
3
  • \$\begingroup\$ I suppose this answer would also be a valid one for the original question. :) (Maybe with n%m assigned to a variable for readability.) \$\endgroup\$
    – Arnauld
    Sep 10, 2018 at 16:22
  • 1
    \$\begingroup\$ Nice! My original solution was 91 bytes. \$\endgroup\$ Sep 10, 2018 at 20:00
  • 1
    \$\begingroup\$ @ceilingcat Actually, m<n should work. \$\endgroup\$
    – Arnauld
    Sep 10, 2018 at 21:12
2
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 134 133 129 bytes

	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

Try it online!

Saved a whole byte by doing string processing rather than arithmetic!

\$\endgroup\$
2
\$\begingroup\$

sed -E, 109 99 97 75 74 bytes

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

Each line of the input is considered a separate number. Try it online.

Explanation:

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

…can be golfed futher, I presume.

\$\endgroup\$
3
  • \$\begingroup\$ Hello and welcome to PPCG. Your answer looks fine, though I do not understand why you added a BADC0FFEE test case. I think the challenge is only about decimal representations. \$\endgroup\$ Sep 12, 2018 at 1:17
  • \$\begingroup\$ You don't need to handle 01010101010 or 000000, according to the challenge spec. Does that save any bytes? \$\endgroup\$
    – Dennis
    Sep 12, 2018 at 1:33
  • \$\begingroup\$ @Dennis Most probably no, as leading zeroes and the ones in between behave the same, so I need to erase them anyway. \$\endgroup\$ Sep 12, 2018 at 1:38
2
\$\begingroup\$

Brainfuck, 147 bytes

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

Try it online! (You will have to tick the box marked "!" and type your input after the "!" on the second line of the code otherwise it will continue asking for inputs forever.)

Its probably not going to be the shortest answer or golfed to the shortest it could be but it was pretty fun to try and do this in Brainfuck so I might as well post it.

As @JoKing pointed out, this program does not remove 0's. I will try and fix this but it might be quite hard.

Explanation:

>>+[[<]>+[>],]                            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
\$\endgroup\$
2
  • \$\begingroup\$ Sorry, but this doesn't remove zeroes as specified. Try it online! \$\endgroup\$
    – Jo King
    Sep 12, 2018 at 13:23
  • \$\begingroup\$ Thanks, I didn't notice that. I'll try and fix that. Whilst I am, I will edit my post \$\endgroup\$
    – FinW
    Sep 12, 2018 at 17:59
2
\$\begingroup\$

APL (Dyalog Unicode), 20 bytes

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

Try it online!

Takes input as a vector of digits. Outputs with a space before and after each +, and includes a variable amount of leading spaces.

This is a train. It is divided into the following.

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

The first function is , this reverses the array, so 1 0 2 becomes 2 0 1.

Then we come into (10×⊢)\, which is applied to the reversed array. This part is inspired by ngn's answer to the Boustrophedonise challenge. Borrowing ngn's explanation, given a vector of digits A B C ..., applying (10×⊢)\ on this vector gives the following.

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×⊢)\ gives 2 0 100.

Next comes 0~⍨. This removes all 0s from the array, giving 2 100.

Finally comes the +s. {⍵'+'⍺}/ is a reduction that starts from the right that concatenates the left arg with a +, followed by the right arg. Effectively, this reverses the array while inserting +s. This gives 100 '+' 2, which is displayed as 100 + 2.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.