Calculate the sum of ILD

21

2

Input:

An integer

Output:

Sum of the input itself + the length of the input + each individual digit of the input.

nr + nr-length + {sum of digits} = output

Examples:

Input: 99
Output: 99 (nr) + 2 (nr-length) + (9 + 9) (digits) → 119

Input: 123
Output: 123 + 3 + (1 + 2 + 3)132

Challenge rules:

  • The input can also contain negative input, which are resolved special. The -/minus-sign is also +1 for the length, and is part of the first digit.
    For example:

    Input: -123
    Output: -123 + 4 + (-1 + 2 + 3)-115

  • You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

General rules:

  • This is , so shortest answer in bytes wins.
    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
  • Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
  • Default Loopholes are forbidden.
  • If possible, please add a link with a test for your code.
  • Also, please add an explanation if necessary.

Test cases:

87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886

Semi-related: Count Sum of all Digits

Kevin Cruijssen

Posted 2016-06-30T08:21:44.560

Reputation: 67 575

I think that with the negative numbers, for example -123 the sum chain should be (-1 + 1 + 2 + 3) instead of (-1 + 2 + 3), right? – Yytsi – 2016-06-30T16:36:39.290

@TuukkaX Nope, it should be -1 + 2 + 3. For this challenge I choose to merge the -/minus-sign to the first digit as one negative digit to make it a bit more interesting. – Kevin Cruijssen – 2016-06-30T17:36:39.420

Answers

10

05AB1E, 28 20 18 8 bytes

ÐgsS'+ýO

Explanation

Ð           # triplicate input
 g          # get length of input
  sS'+ý     # split input and merge with '+' as separator 
       O    # sum and implicitly display

Try it online

Saved 10 bytes thanks to @Adnan

Emigna

Posted 2016-06-30T08:21:44.560

Reputation: 50 798

2

Luckily, 05AB1E does auto-evaluation on arithmetic expressions, so you can do this: ÐgsS'+ýO.

– Adnan – 2016-06-30T09:17:08.210

1@Adnan: Nice! I didn't know that it did. – Emigna – 2016-06-30T09:26:59.063

13

Python 2, 39 bytes

lambda x:x+len(`x`)+eval("+".join(`x`))

Test suite

Using the same eval-trick as in my Pyth-answer.

Denker

Posted 2016-06-30T08:21:44.560

Reputation: 6 639

I never used Python, so forget my possible ignorance, but how does the eval and join know to take the negative first digit for negative input? I would expect -123 to become something like - + 1 + 2 + 3 written out, but apparently it isn't.. (Or is it, and it automatically merged - + 1 to -1 as second step?) – Kevin Cruijssen – 2016-06-30T09:19:08.733

2@KevinCruijssen like you said -123 becomes "-+1+2+3" after joining which yields the correct result when you eval it. Try eval("-+1") for example which results in -1. – Denker – 2016-06-30T09:24:53.047

1@KevinCruijssen - + 1 -> - 1. The unary plus operator exists, so - + 1 is essentially the same as -(+(1)). +a is the same as a, for numbers. – Erik the Outgolfer – 2016-06-30T09:24:56.907

9

Pyth, 11 10 bytes

Thanks to @LeakyNun for a byte!

++vj\+`Ql`

Test suite

Explanation

++vj\+`Ql`QQ  # Q = input, last two implicitly added

  vj\+`Q      # Join the input on '+' and eval it
        l`Q   # Length of the input
           Q  # The input itself
++            # Add those three values to obtain the result

Denker

Posted 2016-06-30T08:21:44.560

Reputation: 6 639

7

CJam, 18

q_,\~__Ab(@g*\~]:+

Try it online

Explanation:

q_      read the input and make a copy
,\      get the string length and swap with the other copy
~__     evaluate the number and make 2 copies
Ab      convert to base A=10 (array of digits), it uses the absolute value
(       take out the first digit
@g*     get a copy of the number, get its sign and multiply with the digit
\~      dump the other digits on the stack
]:+     add everything together

aditsu quit because SE is EVIL

Posted 2016-06-30T08:21:44.560

Reputation: 22 326

6

Brachylog, 35 32 bytes

lL,?:ef+:?:L+I,(0>?h:2*:Ir-:1+.;I.)
lL,(0>?h:1--I;I0),?b:ef+:?:L:I+.

Explanation

lL,             L is the length of the Input
(
    0>?         Input < 0
       h:1--I   I is (First digit - 1) * -1
;               Or
    I0          I is 0
),
?b:ef+          Sum all digits of the Input
      :?:L:I+.  Output = sum of digits + (Input minus first digit) + L + I

Fatalize

Posted 2016-06-30T08:21:44.560

Reputation: 32 976

6

XSLT 1.0 (without EXSLT), 673 bytes

<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"><output method="text"/><param name="i"/><template match="/"><variable name="d"><variable name="s">0<if test="0>$i">1</if></variable><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,$s+2)"/></call-template></variable><value-of select="substring($i,1,$s+1)+$d"/></variable><value-of select="$i+string-length($i)+$d"/></template><template name="d"><param name="i"/>0<if test="$i!=''"><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,2)"/></call-template></variable><value-of select="substring($i,1,1)+$d"/></if></template></transform>

Lightly inflated:

<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <output method="text"/>
    <param name="i"/>
    <template match="/">
        <variable name="d">
            <variable name="s">0<if test="0&gt;$i">1</if></variable>
            <variable name="d">
                <call-template name="d">
                    <with-param name="i" select="substring($i,$s+2)"/>
                </call-template>
            </variable>
            <value-of select="substring($i,1,$s+1)+$d"/>
        </variable>
        <value-of select="$i+string-length($i)+$d"/>
    </template>
    <template name="d">
        <param name="i"/>0<if test="$i!=''">
            <variable name="d">
                <call-template name="d">
                    <with-param name="i" select="substring($i,2)"/>
                </call-template>
            </variable>
            <value-of select="substring($i,1,1)+$d"/>
        </if>
    </template>
</transform>

Run using xsltproc:

xsltproc --param i -87901 ild.xsl ild.xsl

Yes, ild.xsl is passed twice: Once as the XSLT document and then as the XML document to be transformed. An input document must be present because an XSLT processor generally requires one to begin running. (XSLT is designed to define a transformation from an input document to an output document; running a transform solely with command-line parameters as I've done here is atypical.) For this program, any well-formed XML document will suffice as input, and, XSLT being an application of XML, any well-formed XSLT transform is by definition a well-formed XML document.

psmay

Posted 2016-06-30T08:21:44.560

Reputation: 171

1+1 for using something that totally isn't meant for calculating number and making it work anyway. – James – 2016-06-30T18:48:49.150

Can't you remove some quotes to make it "invalid but good for codegolf"? – Erik the Outgolfer – 2016-07-01T10:20:09.777

Surely you don't need space after quotes in name="i" select="..." eg <with-param name="i"select="substring($i,$s+2)"/> ? – cat – 2016-07-01T14:33:37.573

@cat There are only three of those in the entire document, and actually removing the space causes xsltproc to choke. – psmay – 2016-07-01T14:49:33.247

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ I'm not sure I understand the point of submitting a program that doesn't work. – psmay – 2016-07-01T14:49:45.920

1@psmay Oh, that's weird. Erik was saying if you remove the quotes, it can be technically invalid according to the standard but still work properly like HTML, most implementations of which will render tags without quoted attribute values <p id=hello> etc. I guess if xsltproc cares about whitespace it won't let unquoted things by. – cat – 2016-07-01T14:52:26.643

You should note that doc.xml must exist and contain valid XML (i.e, not empty) for this to work. – cat – 2016-07-01T14:56:58.757

4

Dyalog APL, 19 17 16 bytes

≢+#⍎'\d'⎕R'&+',⊢

Takes string and returns

length
+ plus
# in root namespace
evaluation of
'\d'⎕R'&+' regex append digits with a plus
, followed by
the unmodified string

–3 thanks to ngn

Adám

Posted 2016-06-30T08:21:44.560

Reputation: 37 779

4

MATL, 20 bytes

tVtnw48-PZ}t0<?x_]vs

Try it Online

All test cases

Explanation

        % Implicitly grab the input
tV      % Duplicate the input and convert to a string
tn      % Duplicate and find the length of this string
w       % Flip the top two stack elements to get us the string again
48-     % Subtract 48 (ASCII 'O'). Yields a negative number for a negative sign
        % and digits otherwise
P       % Flip the resulting array
Z}      % Break the array up so each element is pushed to the stack
t0<?    % If the first character was a negative sign
  x_    % Pop the negative sign off the stack and negate the first digit
]       % End of if
vs      % Vertically concatenate and sum all stack contents
        % Implicitly display the result

Suever

Posted 2016-06-30T08:21:44.560

Reputation: 10 257

4

Clojure, 102 bytes

(fn[n](load-string(str"(+ "n" "(count(str n))" "(apply str(map #(if(= % \-)%(str %" "))(str n)))")")))

Anonymous function which constructs a string that looks like (+ -123 4 -1 2 3 ) and evals it. Everything pretty verbose as it is, construct string from number, its length, and then map each symbol of string representation of the number except minus to itself plus space and minus remains the same

You can see it running here: https://ideone.com/FG4lsB

cliffroot

Posted 2016-06-30T08:21:44.560

Reputation: 1 080

3

Matlab, 76 67 bytes

n=input('');t=num2str(n)-48;if(n<0)t(1)=0;t(2)=-t(2);end
n+sum(t+1)

9 bytes saved thanks to @Luis Mendo

Explanation:

n=input('');     -- takes input
t=num2str(n)-48; -- makes it a string and then array of digits with "-" becoming -3 (48 is code for 0)
if(n<0)
t(1)=0;          -- set first element (-3) to 0
t(2)=-t(2);      -- the second element is the most significant digit, so we have to negate it
end
n+sum(t+1)       -- take sum of n, sum of all digits and length of t
                    (guaranteed by +1 of every element)

pajonk

Posted 2016-06-30T08:21:44.560

Reputation: 2 480

1sum(t+1)+n is shorter than sum([n numel(t) t]) – Luis Mendo – 2016-07-01T11:10:37.223

1Whoa, I spent a while thinking why this works. Great, thanks! – pajonk – 2016-07-01T13:13:15.537

3

dc, 57 bytes

dc -e"0 1?rdsc*d[1r]s+d0>+dZr[+la10~lc*rdsaZ1<A]sAdsaZ1<Ala+++f"

Explained:

0 1      # Push 0, then 1 on the stack
?        # Wait for input from stdin
         # If input is negative, the leading minus will subtract 1 from 0
r        # Swap (rotate) top two items on stack.
         # Stack status if input (`$') was...
         #       positive                    negative
         # TOP       1     <- coefficient ->    -1
         #           $                           $
         #           0
dsc      # Store a copy of coefficient in `c'
*        # Multiply input by coefficient:
         #  If input was positive, it stays positive.
         #  If input was negative, it's actually interpreted as positive.
         #   In this case, multiply by -1 to make it negative.
d        # Duplicate signed input
[1r]s+   # Define a function `+': Push 1 and rotate
d 0>+    # If input is negative, push 1 underneath the top of the stack
         # This 1 represents the length of the `-` in the input
         # Note that the stack now has 3 items on it, regardless of input sign
dZ       # Push the length of the input (not including leading minus)
r        # Rotate, moving a copy of the input to the top
[        # Begin function definition
 +       # Add top two items of stack
 la      # Load value from `a' (which holds nothing at time of function definition)
 10~     # Slice the last digit off `a' (spoiler: `a' is going to hold the input while
         #  we gather its digits)
 lc*     # Multiply digit by coefficient
         #  Since the input is signed, the input modulo 10 will have the same sign.
         #  We want all digits to be positive, except the leftmost digit, which should
         #   have the sign of the input.
         #  This ensures that each digit is positive.
 r       # Rotate: move remaining digits to top of stack
 dsa     # Store a copy of the remaining digits in `a'
 Z 1<A   # Count the number of digits left; if more than 1, execute A
]sA      # Store the function as `A'
d sa     # Store a copy of the input in `a'
         #  Props to you if you're still reading this
Z 1<A    # Count the number of digits left; if more than 1, execute A
la       # Load leftmost digit of input (still signed appropriately)
+++      # Add the top four items on the stack
f        # Dump stack

This was far more complicated than I had expected! Good challenge :)

Joe

Posted 2016-06-30T08:21:44.560

Reputation: 895

I made a point of not looking at yours until mine was working to see if we had similar approaches... But I see you can get a byte back by swapping your 10~ for a A~! – brhfl – 2016-09-20T18:35:43.770

3

Bash + coreutils, 36 bytes

bc<<<$1+${#1}+$(sed s:\\B:+:g<<<0$1)

Explanation:

     $1+                      # the input number (+)
     ${#1}+                   # the length of the number, the '-' sign included (+)
     $(sed s:\\B:+:g<<<0$1)   # insert '+' between two consecutive word characters
                              #A word character is any letter, digit or underscore.
bc<<<                         # calculate the sum

In sed, \B also matches between two consecutive non-word characters, so for a negative number it matches between '^' and '-'. Note the 0$1 trick needed for \B to give 0-1+2+3, for example.

Run example: 'input.txt' contains all the test cases in the question's statement

while read N;do echo "$N -> "$(./ILD_sum.sh "$N");done < input.txt

Output:

87901 -> 87931
123 -> 132
99 -> 119
5 -> 11
1 -> 3
0 -> 1
-3 -> -4
-99 -> -96
-123 -> -115
-900 -> -905
-87901 -> -87886

seshoumara

Posted 2016-06-30T08:21:44.560

Reputation: 2 878

@DigitalTrauma that won't work for negative integers. – seshoumara – 2016-09-26T06:48:40.130

@DigitalTrauma Well, yes (but code size won't change) and no (if sed is left as is). The reason is that a backslash will be treated differently when using a command substitution with backticks compared to $(). There are two alternative ways to do it with backticks, but both give a 36 bytes solution in the end: sed 's:\B:+:g'<<<0$1 and sed s:\\\B:+:g<<<0$1.

– seshoumara – 2016-09-26T17:20:29.010

2

Java 8, 174 136 122 107 105 93 78 bytes

i->{int f=0;for(int j:(i+"").getBytes())i+=j<48?f++:f-->0?50-j:j-47;return i;}

-14 bytes thanks to @LeakyNun.
-15 bytes thanks to @cliffroot.

Explanation:

Try it online.

i->{                   // Method with integer as both parameter and return-type
  int f=0;             //  Integer-flag, starting at 0
  for(int j:(i+"").getBytes())
                       //  Loop over the digits as bytes
    i+=                //   Increase the input with:
       j<48?           //    If the current byte is '-':
        f++            //     Increase the input with the flag-integer `f` (which is 0),
                       //     and increase the flag-integer `f` by 1 afterwards
       :               //    Else:
        f-->0?         //     If the flag-integer `f` is 1,
                       //     and decrease the flag-integer `f` back to 0 afterwards
         50-j          //      Increase it with 50 minus the current byte
        :              //    Else
         j-47;         //     Increase it with the byte as digit
                       //      + 1 to cover for the length part in ILD
  return i;}           //  Return the modified input as result

Kevin Cruijssen

Posted 2016-06-30T08:21:44.560

Reputation: 67 575

1int c(int i){char[]c=(i+"").toCharArray();int x=i,l=c.length,s=i+l,j=-1;for(;++j<l;x=1)s+=x>0?c[j]-38:38-c[++j];return s;} – Leaky Nun – 2016-06-30T09:47:42.220

1int c(int i){char[]c=(i+"").toCharArray();for(int x=i,j=-1;++j<c.length;i+=1+Integer.parseInt(x<0?"-"+--c[j+=x=1]:c[j]+""));return i;} it finally felt like golfing in Java @LeakyNun does your variant work? it gives wrong answers at first and then crashes. – cliffroot – 2016-06-30T10:07:25.670

@LeakyNun Your code fails at the test case for 0. – Kevin Cruijssen – 2016-06-30T10:08:20.377

Does it work if the x>0 is changed to x>=0? – Leaky Nun – 2016-06-30T10:42:51.310

@LeakyNun Nope, I tried that, but then it gives an incorrect answer for each test-case: 87981; 162; 139; 21; 13; 11; -14; -105; -895; -87856 – Kevin Cruijssen – 2016-06-30T10:44:43.137

1Oh, how ridiculous; change the two occurrences of 38 to 48. – Leaky Nun – 2016-06-30T10:46:37.470

int c(int i){char[]c=(i+"").toCharArray();int x=i,l=c.length,s=i+l,j=-1;for(;++j<l;x=1)s+=x<0?48-c[++j]:c[j]-48;return s;} – Leaky Nun – 2016-06-30T10:51:20.757

1int c(int i){byte[]c=(i+"").getBytes();for(int j=-1;++j<c.length;i+=(c[j]<48?50-c[++j]:c[j]-47));return i;} yay – cliffroot – 2016-06-30T11:32:16.987

@cliffroot When I saw your version and Leaky Nun posted his shorter different approach, I knew you would be able to golf his version some more. ;) Thanks. – Kevin Cruijssen – 2016-06-30T12:38:52.560

2

C#, 118 bytes

int k(int a){var s=a.ToString();for(int i=0;i<s.Length;a+=s[i]<46?-(s[++i]-48)+ ++i-i:(s[i++]-48));return a+s.Length;}

ScifiDeath

Posted 2016-06-30T08:21:44.560

Reputation: 151

The fact you need the space in 1+ ++i is completely ridiculous imo – cat – 2016-06-30T23:04:12.047

you're right but i didn't know how to do it without this... – ScifiDeath – 2016-07-01T04:28:39.943

1you can do s[i]<46 to check for minus – cliffroot – 2016-07-01T07:59:31.550

@ScifiDeath Can't you do ++i+1? – Erik the Outgolfer – 2016-07-01T10:21:47.353

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ No, because of infix math's dumb order of evaluation – cat – 2016-07-01T14:29:34.423

@cat I thought prefix ++ has higher priority than binary +. So, anyways, why you can't do 1+++i? Is it taken as 1++ +i? If yes, you're helpless. – Erik the Outgolfer – 2016-07-01T14:35:00.623

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ It does but in his use case it's ..aBigExpression+ ++i... so he can't just flip the operands without adding lots of parentheses. – cat – 2016-07-01T14:39:40.330

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ csharp> var i = 0; 1+++i gives (1,14): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer but csharp> 1+ ++i gives 2 – cat – 2016-07-01T14:42:00.797

2

C#, 106 bytes

I beat java my a byte, my life is complete

int r(int n){var s=n+"";return n+s.Length+s.Select((k,j)=>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();}

Ungolfed (kinda)

    public static int r(int n)
    {
            var s = n + "";
            return n + s.Length + s.Select((k, j) =>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();
    }

downrep_nation

Posted 2016-06-30T08:21:44.560

Reputation: 1 152

2pretty sure you can replace string with var and '-' with 45 – ScifiDeath – 2016-06-30T22:23:59.917

you can do (n)=>{.... for an anonymous lambda – cat – 2016-07-01T15:27:33.373

cat could you elaborate? im trying to figure it out by myself but its not working for me. i never did that – downrep_nation – 2016-07-01T17:48:06.760

I know it's been a while, but you can golf it to 89 bytes: n=>n+(n+"").Length+(n+"").Select((k,j)=>int.Parse((n+"")[k<48?1:j]+"")*(k<48?-2:1)).Sum() Although you'll have to add +18 for using System.Linq; which you also forgot in your current answer.

– Kevin Cruijssen – 2018-02-16T15:41:04.403

2

PowerShell v4, 48 bytes

param($n)$n,"$n".length+[char[]]"$n"-join'+'|iex

This should work in v2+, but I only tested in v4.

Takes input $n. Creates a new array with the , operator consisting of $n and the .length when $n is converted to a string. Concatenates with that the string $n cast as a char-array. Then, that whole array is -joined together with + before being piped to iex (similar to eval). The result is left on the pipeline and output is implicit.

For example, for input -123, the array would look like (-123, 4, -, 1, 2, 3), and the string after the -join would look like -123+4+-+1+2+3. Then the Invoke-Expression happens, and the result is -115 as expected.

AdmBorkBork

Posted 2016-06-30T08:21:44.560

Reputation: 41 581

2

Factor with load-all, 175 bytes

Well, this is not very short. The special handling of unary minus is really annoying; I guess I could do it better and I will, maybe.

[ dup [ 10 >base length ] [ [ 10 >base >array [ 48 - ] V{ } map-as ] [ 0 < ] bi [ reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip ] [ ] if 0 [ + ] reduce ] bi + + ]

Using this substitution regex:

s/(-?[\d]+)\s*->\s*(-?[\d]+)/{ $2 } [ $1 calculate-ild ] unit-test/g

We can turn the OP's test cases into a Factor test suite.

USING: arrays kernel math math.parser sequences ;
IN: sum-ild

: sum-digits ( n -- x )
    [ number>string >array [ 48 - ] V{ } map-as ]
    [ 0 < ]
    bi
    [
      reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip
    ]
    [ ] if
    0 [ + ] reduce ;

: calculate-ild ( n -- x )
  dup
  [ number>string length ]
  [ sum-digits ]
  bi + + ;

USING: tools.test sum-ild ;
IN: sum-ild.tests

{ 87931 } [ 87901 calculate-ild ] unit-test
{ 132 } [ 123 calculate-ild ] unit-test
{ 119 } [ 99 calculate-ild ] unit-test
{ 11 } [ 5 calculate-ild ] unit-test
{ 3 } [ 1 calculate-ild ] unit-test
{ 1 } [ 0 calculate-ild ] unit-test
{ -4 } [ -3 calculate-ild ] unit-test
{ -115 } [ -123 calculate-ild ] unit-test
{ -905 } [ -900 calculate-ild ] unit-test
{ -87886 } [ -87901 calculate-ild ] unit-test

cat

Posted 2016-06-30T08:21:44.560

Reputation: 4 989

2

SpecBAS - 147 bytes

1 INPUT a$: l=LEN a$: b$="text "+a$+"+"+STR$ l+"+": FOR i=1 TO l: b$=b$+a$(i)+("+" AND i<l): NEXT i: EXECUTE b$

Builds up a string which then gets run. Unfortunately EXECUTE doesn't work with the ? shorthand for PRINT, but TEXT saved 1 character.

enter image description here

Brian

Posted 2016-06-30T08:21:44.560

Reputation: 1 209

1

AWK, 64 63 61 bytes

{s=j=0;for(;j++<n=split($1,a,"");s+=$1>0||j-2?a[j]:-a[j]);$0+=n+s}1

Try it online!

TIO link has 6 extra bytes s=j=0; to allow for multi-line input. This is the shortest method I could come up with. I'm curious if it can be done shorter in AWK.

Saved 2-bytes, thanks Kevin

Robert Benson

Posted 2016-06-30T08:21:44.560

Reputation: 1 339

1Can't $0=n+s+$0 be golfed to $0+=n+s (-2 bytes)? – Kevin Cruijssen – 2018-02-16T17:26:38.070

You are absolutely right @KevinCruijssen . Silly me. – Robert Benson – 2018-02-18T03:22:17.820

1

Perl 5, 22 + 1 (-p) = 23 bytes

$_+=eval s//+/gr.y///c

Try it online!

Xcali

Posted 2016-06-30T08:21:44.560

Reputation: 7 671

1

Add++, 15 bytes

L,bU"+"jvAbLAvs

Try it online!

How it works

L,		; Create a lambda function. Takes a string argument
		; Example argument: 	['123']
	bU	; Unpack;	STACK = ['1' '2' '3']
	"+"j	; Join with +;	STACK = ['1+2+3']
	v	; Evaluate;	STACK = [6]
	AbL	; Arg length;	STACK = [6 3]
	Av	; Int argument;	STACK = [6 3 123]
	s	; Sum;		STACK = [132]

caird coinheringaahing

Posted 2016-06-30T08:21:44.560

Reputation: 13 702

1

JavaScript (ES6), 38 bytes

n=>eval([n+=``,n.length,...n].join`+`)

Uses the old join-and-eval trick. Save 4 bytes if I can insist on string input:

f=
n=>eval([n,n.length,...n].join`+`)
;
<input type=number oninput=o.value=f(this.value)><input id=o readonly>

Neil

Posted 2016-06-30T08:21:44.560

Reputation: 95 035

"Add 4 bytes if I have to allow both integers and strings representing integers" You don't, it is optional to choose either, but probably 99.9% will choose integer. I mainly added it for the rare languages that only support strings, but I will remove that part from my question since almost every language does. – Kevin Cruijssen – 2016-06-30T12:43:07.690

@KevinCruijssen Sorry for being unclear earlier; the 34-byte version only works on strings. – Neil – 2016-06-30T13:33:11.450

1

Perl 6 - 30 bytes

As literal as it gets

{$^a+$^a.chars+[+]($^a.comb)}

Use it as an anonymous function

> {$^a+$^a.chars+[+]($^a.comb)}(99)
119 

malkaroee

Posted 2016-06-30T08:21:44.560

Reputation: 332

1

C++, 255 Bytes

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
    string input;
    cin >> input;
    int sum = atoi(input.c_str()) + input.length();
    for(unsigned i = 0; i < input.length(); ++i)
        sum += input.at(i) - 48;
    return 0;
}

tachma

Posted 2016-06-30T08:21:44.560

Reputation: 21

1

Perl 5 - 37 Bytes

warn eval(join'+',/./g)+($_+=()=/./g)

Input is in $_

Kaundur

Posted 2016-06-30T08:21:44.560

Reputation: 71

1

C, 132 116 113 80

t,c;f(char*v){for(c=atoi(v+=t=*v==45);*v;t=0,++v)c+=t?50-*v-2*c:*v-47;return c;}

Function f() takes the input as a string and returns the result as an integer. Full program version (113 bytes):

t;main(int c,char**v){char*p=v[1];c=atoi(p+=t=*p==45);for(c=t?-c:c;*p;++p,t=0)c+=t?50-*p:*p-47;printf("%d\n",c);}

Requires one argument.

owacoder

Posted 2016-06-30T08:21:44.560

Reputation: 1 556

1

Javascript (using external library) (45 bytes)

Using a library I wrote to bring LINQ to Javascript, I was able to write the following:

(i)=>i+(i+"").length+_.From(i+"").Sum(x=>x|0)

enter image description here

applejacks01

Posted 2016-06-30T08:21:44.560

Reputation: 989

1Link to library? – phase – 2016-07-06T21:29:44.840

https://github.com/mvegh1/Enumerable . No docs yet, sorry – applejacks01 – 2016-07-06T21:34:27.963

1

Perl, 27 bytes

22 bytes code + 5 for -paF.

$"="+";$_+=@F+eval"@F"

Explanation

Uses the -a autosplit option with an empty delimiter (-F) creating an array of the digits passed in. Uses the magic variable $" which controls which char is used to join an array when it's interpolated into a string (we use "+" here) and the fact that a list used in scalar context will return the length of the list (the number of digits).

Usage

echo -n 99 | perl -paF -e'$"="+";$_+=@F+eval"@F"'
119

Perl, 27 bytes

22 bytes code + 5 for -paF.

Alternative solution, that's a lot more readable for no more bytes. I prefer the other as it looks more cryptic!

$_+=@F+eval join"+",@F

Dom Hastings

Posted 2016-06-30T08:21:44.560

Reputation: 16 415

1

dc, 56 bytes

?dZrdd1sa[1+r0r-_1sa]sb0>b[A~rd0<x]dsxxrla*[+z1<y]dsyxp

No shorter than Joe's above, but a somewhat different implementation (and one that takes negative numbers as input vs. a subtraction command). Can probably be golfed more, but lunch only lasts so long.

?                #input
dZrdd            #find no. of digits, rotate to bottom of stack, dup input twice
1sa              #coefficient for first digit stored in register 'a'
[1+r0r-_1sa]sb   #macro 'b' executes on negative numbers. add one (for the neg. sign)
                 #rotate this value out of the way, leave a positive copy on top
0>b              #run the above macro if negative
[A~rd0<x]dsxx    #create and run macro 'x'; mod 10 to grab least significant digit
                 #keep doing it if quotient is greater than zero
rla*             #a zero remains in the way of our most significant digit, rotate it down
                 #and multiply said digit by our coefficient 'a' from earlier
[+z1<y]dsyx      #add two top stack values (we left that zero there to ensure this always
                 #works), check stack depth and keep doing it while there's stack
p                #print!

brhfl

Posted 2016-06-30T08:21:44.560

Reputation: 1 291

1

RProgN, 30 Bytes

] '' . ] '-?.' | sum _ \ L + +

Explination

]               # Clone the input
                #
'' . ]          # Convert it to a string, then clone it again.
'-?.' | sum     # Split it into chunks via the pattern '-?.' (A - if there is one, followed by a single character). Sum the resulting array.
_               # Floor the value, purely because I hate floats.
\ L + +         # Swap the top value with the value underneith it, to work with the string again. Get it's length, add the top, middle, and bottom, which is now the length, the sum and the input respectively.

Try it Online!

ATaco

Posted 2016-06-30T08:21:44.560

Reputation: 7 898

1

R, 108 bytes

A bit late to the party again but here it goes:

s=strsplit(paste(n<-scan()),"")[[1]];n+nchar(n)+sum(as.integer(if(n<0)c(paste0(s[1],s[2]),s[1:2*-1])else s))

In order to generally split the digits of any number (e.g. to sum them), R requires us to first convert to a string and subsequently split the string into a string vector. To sum up the elements, the string vector has to be converted to numeric or integer. This together with the exception with the sum of a the digits of a negative number eats up a lot of bytes.

The exception can be golfed a bit (to 96 bytes) if warning messages are allowed.

s=as.integer(strsplit(paste(n<-scan()),"")[[1]]);if(n<0){s[2]=s[2]*-1;s=s[-1]};n+nchar(n)+sum(s)

In this case the string vector is converted to integer directly using as.integer. However, for negative numbers the first element in the vector will be a minus sign: "-". This causes some trouble, e.g.: as.numeric(c("-",1,2,3)) will return NA 1 2 3 and a warning message. To circumvent this, remove the NA and then multiply the first element with -1 before taking the sum.

Billywob

Posted 2016-06-30T08:21:44.560

Reputation: 3 363

0

C# 77 bytes

Check it here

Golfed:

int r(int n){return n+(n+"").Length+(n+"").Select(c=>int.Parse(c+"")).Sum();}

Ungolfed:

 public int r(int n)
 {
     var t = n + (n+"").Length;
     t += (n + "").Select(c => int.(c + "")).Sum();
     return t;
 }

Quintonn

Posted 2016-06-30T08:21:44.560

Reputation: 101

Hi, welcome to PPCG! Although it is quite a bit shorter than both other C# answers so far, it fails to comply to the -/minus rule: -123 -> -123 + 4 + (-1 + 2 + 3) -> -115. Also, one small tip for your current code, you can remove the spaces between c=>int. Again welcome, and enjoy your stay. :) – Kevin Cruijssen – 2016-09-20T12:18:30.530

2Sure this complies with ”you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs”? Looks like a snippet using a variable appearing from nowhere. – manatwork – 2016-09-20T12:39:25.250

As it stands, this is invalid and needs to be fixed or deleted. – Rɪᴋᴇʀ – 2016-09-20T13:59:12.203

I tried to fix my answer, is it still invalid? – Quintonn – 2016-09-20T19:33:46.250

-1

Pyt, 7 bytes

ĐąŁ⇹ĐŚƩ

Try it online!

Shortest as of now!

Đ         duplicate
 ąŁ       convert to array of digits, pop, and push length
   ⇹Đ     swap top two values and duplicate
     ŚƩ   sum of digits and sum everything on stack

FantaC

Posted 2016-06-30T08:21:44.560

Reputation: 1 425

2Hi. This seems to fail for all negative test cases. – Kevin Cruijssen – 2018-02-18T11:05:03.297