# Calculator that adds char values

Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.

Example

Input
Hello World!

Output
1085


# Rules

The calculator needs to accept just ASCII encoding.

The shortest code wins.

# Notes

Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.
So I leave it as a bonus thing aswell.
The calculator should be run as written, so no need to modify before compiling or interpreting.

# Bonus

Thanks to Synthetica, here is one more bonus,

The program that has the lowest output when you use its code as its input wins gets a star.

I don't want to modify it completly.

If you write it additional to output the (right) value in UTF-8 you get a star.

The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.

Web codes will run first under IE11 with chakra and then in FireFox 29.0.1 with SpiderMonkey

Linux code will run on a Raspberry Pi with Raspbian.

The teststring is this:

q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/Eks(D'$z$\6Ac+MT&[s[]_Y(<g%"w%cW'c&q)D$0#C$QGf>?A$iawvc,}9!('c&q)D$0#C$QGf>?A$iawvc,}9!(


Have fun coding :)

# Bonusscoring

I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)

You can download the code I gonna use for testing here feel free to fork and improve it :)

Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(

• I get 1085 for Hello World! using two different languages for ASCII values on my computer. – Kyle Kanos Jun 5 '14 at 14:21
• He probably forgot to add the '!'. edit you were 3 seconds faster... – gxtaillon Jun 5 '14 at 14:22
• Could one please explain the downvotes? – Knerd Jun 5 '14 at 14:33
• My guess is that the downvotes indicate that it's not really a good problem. – Kyle Kanos Jun 5 '14 at 14:37
• @Knerd mainly, because it's a bit too trivial in most languages (as you can see from the length of the submissions you already got) – Martin Ender Jun 5 '14 at 14:43

## Java 8 - 79 bytes (non-competing)

interface C{static void main(String[]a){System.out.print(a[0].chars().sum());}}


## JavaScript function golf, 77 bytes (non-competing)

var s=i();var x=0;for(var i1=0;i1<sl(s);i1++){x+=schca(s,i1);}console.log(x);


Yes, you got it right, it's my own function golf again. It recently got a string functions update.

The language was created after the challenge, so it's non-competing.

Validity source:

>>> var s=i();var x=0;for(var i1=0;i1<sl(s);i1++){x+=schca(s,i1);}console.log(x);
Hello World!
1085


Bonus score:

>>> var s=i();var x=0;for(var i1=0;i1<sl(s);i1++){x+=schca(s,i1);}console.log(x);
var s=i();var x=0;for(var i1=0;i1<sl(s);i1++){x+=schca(s,i1);}console.log(x);
6276


# Java 8, 113 chars

BigInteger C(String s){BigInteger i=BigInteger.ZERO;s.chars().forEach(x->i=i.add(BigInteger.valueOf());return i;}


Note each character in Java is Unicode 1-4 bytes unsigned integer, using sum function would easily overflow.

Detailed

BigInteger C (String s)
{
BigInteger i = BigInteger.ZERO;

return i;
}


# Java 8, 57 chars

ASCII only solution

int C(String s){return s.chars().filter(x->x<128).sum();}


Detailed try here

public static int C (String s)
{
return s
.chars() // stream the characters
.filter(x -> x < 128) // filter ASCII (optional)
.sum(); // return the sum
}

• Maybe you misunderstood -- you must work with at least ASCII, so there is no reason for you to filter ascii. – cat Apr 22 '16 at 2:28
• @cat I fixed it now, the solution wouldn't work for unicode since int would easily overflow even if you just sum two characters with higher than 2^32 / 2 – Khaled.K Apr 22 '16 at 8:38
• 101 bytes including BigInteger import. Also, your current submission fails to compile (variable referenced in lambda must be final or effectively final) – Benjamin Urquhart Jun 19 '19 at 16:21
• 18 bytes for the (unfiltered) ascii-only version – Benjamin Urquhart Jun 19 '19 at 16:23

# Unipants' Golfing Language, 8 bytes

cIl+I:_o


Try it online!

Returns 660 given its own source code.

## Explanation

cIl+I:_o
c        # Create an integer. We need it - you'll see why.
I       # Input the first character.
l  :   # While loop.
+     # Add the character value to the integer. This is
# why we needed an integer. Otherwise, there would
# only be 1 item in a stack now, and the "+" op is
# not defined for this case. In fact, it returns 0
I    # Input the next character.
_  # Discard a zero (the zero from the last input,
# representing the End Of Line).
o # Output the result.


# JavaScript (ES6), 37 bytes

f=([c,...a])=>c?c.charCodeAt()+f(a):0


This uses a handy feature, new in ES6: destructuring assignments. When run, the variable c gets set to the first char in the string, and a gets set to the rest of the string as an array.

# Cubix, 10 bytes

OU@;i)!^(+


Test it online!

This is almost the perfect challenge for Cubix, which can only input one char code at a time. This code expands to the following cube net:

    O U
@ ;
i ) ! ^ ( + . .
. . . . . . . .
. .
. .


The code is then run, starting at the i and facing east. Here's the main loop:

• i - input a char code from STDIN and push it to the stack. Pushes -1 on EOF.
• ) - increment the top item.
• ! - if the top item is non-zero, skip the next instruction.
• ( - decrement the top item.
• + - add the top two items. Note: the stack has infinite zeroes at the bottom.
• . - no-op.

When EOF is reached, the ! fails, and ^ forces the instruction pointer to move north onto the top face. Then this code is run:

• ; - pop the top item (currently a 0).
• U - turn 180 degrees counter-clockwise. This is used to fit ;O@ on the top face.
• O - output the top item (sum of char-codes) as a number.
• @ - terminate the program.
• I think ..;Oi?.@/+ works for the same byte count (and less instructions :P ) – FlipTack Dec 24 '16 at 10:59
• @Flp.Tkc That doesn't work on null bytes though, although perhaps "The calculator needs to accept just ASCII encoding" means it won't ever need to – ETHproductions Dec 24 '16 at 11:54

# Minkolang, 6 bytes

$o$+N.


Try it online!

### Explanation

$o takes all characters from input as chars (the characters are automatically converted to their character codes)$+         sum up all the values
N.         output as number and end program


# 05AB1E, 2 bytes

ÇO


Try it online.

Explanation:

Ç   # Convert each character in the (implicit) input to its unicode value
O  # Sum this list of integers
# (after which the result is output implicitly)


# PHP, 46 bytes

No PHP answer on this yet, so here's the easy one:

<?=array_sum(array_map(ord,str_split($argn)));  Try it online! $ echo Hello World!|php -F addascii.php
1085


48 bytes

Iterative:

foreach(str_split($argn)as$s)$x+=ord($s);echo$x;  Try it online! 51 bytes Iterative 2: while($i<strlen($argn))$x+=ord($argn[$i++]);echo$x;  Try it online! 63 bytes Recursive: function f($s,$c=0){return$s?f(substr($s,1),ord($s[0])+$c):$c;}


Try it online!

69 bytes

Using PHP's rarely used [citation needed] array_reduce() function:

<?=array_reduce(str_split($argn),function($c,$i){return$c+ord($i);});  Try it online! # Keg, 2 bytes ?⅀  Try it online! ## Explanation ? # Read the full input string ⅀ # Sum the whole stack # Implicit output  • 2 bytes – Lyxal Dec 4 '19 at 4:57 ## W, 2 bytes The Join function also works with numbers. CJ  ## W, 4 bytes Terribly golfed answer... C@+R  # Lua 57 a=io.read();b=0;for i=1,#a do b=b+a.byte(a,i)end print(b)  Sucks that it's the longest by a long shot, but whatever. ## C 63 main(a,b)char**b;{a+=*b[1];*b[1]++?main(a,b):printf("%d",a-2);}  • Compileonline is giving me Segmentation fault (core dumped). Any tips? – user21677 Jun 5 '14 at 21:20 • @tolos: Yes, it expects input as a command line argument which ideone won;t support – Abhijit Jun 5 '14 at 21:32 • Is this acutal C? Which IDE/Compiler are you using? Visual Studio 2013 doesn't accept it. – Knerd Jun 6 '14 at 15:02 • I compiled with VS2012, yet to install 2013. Note, you actually have to compile as a C Program not as a C++ to make this work – Abhijit Jun 6 '14 at 15:34 • Ok, didn't know that. I gonna try it as C programm later. – Knerd Jun 6 '14 at 23:12 # Perl 33 $_=<>;$x+=ord for split'';print$x


I don't know Perl too well. I'm sure it can be golfed some more.

• Nice short answer. Think needs a chomp somewhere though, as gives 1095 as answer to Hello World! instead of 1085. – steve Oct 7 '15 at 17:46

# Cobra - 81

class P
def main
for i in c,d+=i to int
print d


Console.ReadLine().Sum(i=>i)

• Will it execute as it is written? See the notes ;) – Knerd Jun 5 '14 at 20:07
• Edited and fixed. – Jacob Jun 5 '14 at 20:24
• Won't execute, you are missing the using System; part. – Knerd Jun 5 '14 at 20:37
• Ok, since I'm a LINQPad-addicted, I tend to forget those envrionment things. I decided to edit the title ;) and I think now it works just fine. – Jacob Jun 6 '14 at 4:45
• Yeah, should work. For the speed test I gonna add the environment stuff ;) – Knerd Jun 6 '14 at 7:06

## J (9 chars)

In the REPL, we only need 6 chars:

   +/a.i.'Hello World!'
1085


To make it a re-usable program, we need to add 3 chars of decoration:

   as=: [: +/ a.&i.
as 'Hello World!'
1085


## Common Lisp, 35

(reduce'+(read-line):key'char-code)


Produces 3053 when given its own code.

# ><>, 19 bytes

0i:1+?!v+!
;n~<


It does work on Unicode. For example, this correctly outputs 27272 : ⚳ℚ⊻

Try it here

• I don't think that this deserves its own answer, so here's a 14 byte version (split into two lines): ii:0(7$.+!, ~n;. 0 in place of i would work, too. An alternate 17 byte version of yours would be ii:0(?v+!, ;n~< (again, in two lines - this time without whitespace on the second) – cole Oct 9 '15 at 3:39 ## Perl 22 s/./$t+=ord$&/eg;say$t


sample:

perl -nE 's/./$t+=ord$&/eg;say$t' < <(echo -n Hello\ World\!) 1085  ## Perl, 34322725 21+1=22 bytes Added 2 due to the need for -p flags. Thanks to @manatwork for the guidance. $a+=ord for/./g;$_=$a


Test:

echo 'Hello World!' | perl -pe '$a+=ord for/./g;$_=$a' 1085  • No need for parenthesis around the statement modifier's expression. And no need to explicitly assign the input to $_ – after all, that makes it default variable. $a+=ord for<>=~/./g;print$a – manatwork Oct 7 '15 at 19:19
• As both -n and -p cost the same 1 character, better use the later and replace print$a$_=$a. – manatwork Oct 7 '15 at 19:25 # Java, 144 bytes (sum of 13067) interface S{static void main(String[]A){int I=0;for(char J:new java.util.Scanner(System.in).nextLine().toCharArray())I+=J;System.out.print(I);}}  # Mathematica, 19 bytes Tr@*ToCharacterCode  Test case: Tr@*ToCharacterCode@"Hello World!" (* 1085 *)  # 𝔼𝕊𝕄𝕚𝕟 2, 5 chars / 13 bytes (noncompetitive) ⨭ ᴉ⒨⒞  Try it here (Firefox only). Splits and maps the input to its charcodes, then sums the resulting array. # jq, 12 characters (11 characters code + 1 character command line option.) explode|add  Sample run: bash-4.3$ bin/jq -R 'explode|add' <<< 'Hello World!'
1085


On-line test (Passing -R through URL is not supported – so input passed as string "Hello World!".)

(CW because explode appeared in jq 1.4, released 4 days after this question.)

Uses Mathcad's built-in vector summation operator. As "whatever" is an input method, the user types the word directly into the argument for the function str2vec (which converts a string to a vector of its character codes).

## C++, 131 140 bytes

### Golfed:

#include<iostream>
int main(){int a=0;std::string x;getline(std::cin,x);for(int c=0;c<x.length();c++){a=a+(int)x[c];}std::cout<<a;}


### Ungolfed:

#include<iostream>

int main(){
int a = 0;
std::string x;
getline(std::cin, x);
for(int c = 0; c < x.length(); c++){
a = a + (int) x[c];
}
std::cout<<a;
}


## Java, 139 Bytes

//takes input from cmd line args

class P {public static void main(String a[]){String s=a[0];int v=0;for(int i=0;i<s.length();i++){v+=(int)s.charAt(i);}System.out.print(v);}}


It's big, but yeah.

# Factor, 3 bytes

sum


Strings are sequences, arrays of char values. sum is basically 0 [ + ] reduce (or, equivalently, [ + ] foldl), so this sums the chars in a string.