The Wayback Machine - https://web.archive.org/web/20160701200659/http://codegolf.stackexchange.com/questions/84071/calculate-the-sum-of-ild
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Input:

An integer

Output:

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

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

For example:

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 never 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, full programs. Your call.
  • Default loopholes are forbidden.
  • If possible, please add a link with a test for your code.

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

share|improve this question
    
Yes, it has been in the sandbox since June 15th. – Kevin Cruijssenyesterday
    
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? – TuukkaXyesterday
    
@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 Cruijssenyesterday

19 Answers 19

Python 2, 39 bytes

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

Test suite

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

share|improve this answer
    
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 Cruijssenyesterday
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. – DenkerAffeyesterday
    
@KevinCruijssen - + 1 -> - 1. The unary plus operator exists, so - + 1 is essentially the same as -(+(1)). +a is the same as a, for numbers. – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀyesterday

05AB1E, 282018 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

share|improve this answer
1  
Luckily, 05AB1E does auto-evaluation on arithmetic expressions, so you can do this: ÐgsS'+ýO. – Adnanyesterday
    
@Adnan: Nice! I didn't know that it did. – Emignayesterday

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 
share|improve this answer

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 
share|improve this answer

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 
share|improve this answer

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.

share|improve this answer
    
+1 for using something that totally isn't meant for calculating number and making it work anyway. – Dr Green Eggs and Iron Manyesterday
    
Can't you remove some quotes to make it "invalid but good for codegolf"? – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ9 hours ago
    
Surely you don't need space after quotes in name="i" select="..." eg <with-param name="i"select="substring($i,$s+2)"/> ? – cat5 hours ago
    
@cat There are only three of those in the entire document, and actually removing the space causes xsltproc to choke. – psmay5 hours ago
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. – cat5 hours ago

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 
share|improve this answer

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) 
share|improve this answer
1  
sum(t+1)+n is shorter than sum([n numel(t) t]) – Luis Mendo8 hours ago
1  
Whoa, I spent a while thinking why this works. Great, thanks! – pajonk6 hours ago

Java 7, 174136122 107 bytes

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

Golfed a lot thanks to @LeakyNun and @cliffroot.

Why did I made that special rule about negative input? xD

Full program & test cases:

Try it here. (Not the latest version since ideone doesn't work atm..)

class Main{ static int 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; } public static void main(String[] a){ System.out.println(c(87901)); System.out.println(c(123)); System.out.println(c(99)); System.out.println(c(5)); System.out.println(c(1)); System.out.println(c(0)); System.out.println(c(-3)); System.out.println(c(-123)); System.out.println(c(-900)); System.out.println(c(-87901)); } } 

Output:

87931 132 119 11 3 1 -4 -115 -905 -87886 
share|improve this answer
1  
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?c[j]-38:38-c[++j];return s;} – Leaky Nunyesterday
1  
int 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. – cliffrootyesterday
    
@LeakyNun Your code fails at the test case for 0. – Kevin Cruijssenyesterday
1  
Oh, how ridiculous; change the two occurrences of 38 to 48. – Leaky Nunyesterday
1  
int 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 – cliffrootyesterday

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;} 
share|improve this answer
    
The fact you need the space in 1+ ++i is completely ridiculous imo – cat21 hours ago
    
you're right but i didn't know how to do it without this... – ScifiDeath15 hours ago
1  
you can do s[i]<46 to check for minus – cliffroot12 hours ago
    
@ScifiDeath Can't you do ++i+1? – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ9 hours ago
    
@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ No, because of infix math's dumb order of evaluation – cat5 hours ago

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

share|improve this answer

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

share|improve this answer

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(); } 
share|improve this answer
2  
pretty sure you can replace string with var and '-' with 45 – ScifiDeath21 hours ago
    
you can do (n)=>{.... for an anonymous lambda – cat4 hours ago
    
cat could you elaborate? im trying to figure it out by myself but its not working for me. i never did that – downrep_nation2 hours ago

Dyalog APL, 19 17 bytes

≢+(⍎'\d'⎕R'&+',⊢) 

Takes string and returns

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

–2 thanks to ngn

share|improve this answer

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 
share|improve this answer

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>

share|improve this answer
    
"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 Cruijssenyesterday
    
@KevinCruijssen Sorry for being unclear earlier; the 34-byte version only works on strings. – Neilyesterday

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.

share|improve this answer

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 
share|improve this answer

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; } 
share|improve this answer

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

close