20
\$\begingroup\$

Task

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#/E`ks(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 :(

\$\endgroup\$
17
  • 3
    \$\begingroup\$ I get 1085 for Hello World! using two different languages for ASCII values on my computer. \$\endgroup\$
    – Kyle Kanos
    Jun 5, 2014 at 14:21
  • 1
    \$\begingroup\$ He probably forgot to add the '!'. edit you were 3 seconds faster... \$\endgroup\$
    – gxtaillon
    Jun 5, 2014 at 14:22
  • 1
    \$\begingroup\$ Could one please explain the downvotes? \$\endgroup\$
    – Knerd
    Jun 5, 2014 at 14:33
  • 3
    \$\begingroup\$ My guess is that the downvotes indicate that it's not really a good problem. \$\endgroup\$
    – Kyle Kanos
    Jun 5, 2014 at 14:37
  • 5
    \$\begingroup\$ @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) \$\endgroup\$ Jun 5, 2014 at 14:43

83 Answers 83

1
\$\begingroup\$

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

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.

\$\endgroup\$
1
\$\begingroup\$

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.
\$\endgroup\$
2
  • \$\begingroup\$ I think ..;Oi?.@/+ works for the same byte count (and less instructions :P ) \$\endgroup\$
    – FlipTack
    Dec 24, 2016 at 10:59
  • \$\begingroup\$ @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 \$\endgroup\$ Dec 24, 2016 at 11:54
1
\$\begingroup\$

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

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

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

More non-competing answers:

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!

\$\endgroup\$
1
\$\begingroup\$

Keg, 2 bytes

?⅀

Try it online!

Explanation

?  # Read the full input string
 ⅀ # Sum the whole stack
# Implicit output
\$\endgroup\$
1
  • \$\begingroup\$ 2 bytes \$\endgroup\$
    – lyxal
    Dec 4, 2019 at 4:57
1
\$\begingroup\$

W, 2 bytes

The Join function also works with numbers.

CJ

W, 4 bytes

Terribly golfed answer...

C@+R
\$\endgroup\$
1
\$\begingroup\$

Japt, 6 bytes

U¬mc x

Pretty simple. Try it online!

How it works

U¬mc x  // Implicit: U = input string
U¬      // Split U into chars.
  mc    // Map each item to its char code.
     x  // Sum.
        // Implicit: output last expression
\$\endgroup\$
4
  • \$\begingroup\$ Out of curiosity, why didn't you assign ¬ to a negation of some sort? \$\endgroup\$ Jan 6, 2016 at 0:49
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Because I was in a hurry and just assigned them as I saw need, without planning ahead. I have a set that makes more sense ready to be rolled out, by changing one line of code, but I'm leery about that because it'd invalidate nearly every existing answer. \$\endgroup\$ Jan 6, 2016 at 19:51
  • \$\begingroup\$ That's an easy fix. Add a conditional to the header (e.g., url/interpreter.html#new=1); anything without it uses the old character set, and anything with it uses the new character set. \$\endgroup\$ Jan 6, 2016 at 19:53
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, I'll consider that. \$\endgroup\$ Jan 6, 2016 at 19:54
1
\$\begingroup\$

JavaScript function golf, 77 bytes

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

I made this for you!

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

Java 8 - 79 bytes

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

PlatyPar, 2 bytes

us

Try it online!

u generates an array of all charcode values in the input string, and s finds their sum.

When run on itself, it returns 232.

This is similar to Conor's Jolf answer, except that I use a byte to convert the string into an array of character codes (which is implicit in Jolf), whereas he uses a byte to retrieve the input (which is implicit in PlatyPar).

\$\endgroup\$
1
\$\begingroup\$

Fig, \$1\log_{256}(96)\approx\$ 0.823 bytes

S

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ imagine my disappointment when I scroll down \$\endgroup\$
    – Seggan
    Oct 11, 2022 at 21:06
0
\$\begingroup\$

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.

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

C 63

main(a,b)char**b;{a+=*b[1];*b[1]++?main(a,b):printf("%d",a-2);}
\$\endgroup\$
5
  • \$\begingroup\$ Compileonline is giving me Segmentation fault (core dumped). Any tips? \$\endgroup\$
    – user21677
    Jun 5, 2014 at 21:20
  • \$\begingroup\$ @tolos: Yes, it expects input as a command line argument which ideone won;t support \$\endgroup\$
    – Abhijit
    Jun 5, 2014 at 21:32
  • \$\begingroup\$ Is this acutal C? Which IDE/Compiler are you using? Visual Studio 2013 doesn't accept it. \$\endgroup\$
    – Knerd
    Jun 6, 2014 at 15:02
  • \$\begingroup\$ 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 \$\endgroup\$
    – Abhijit
    Jun 6, 2014 at 15:34
  • \$\begingroup\$ Ok, didn't know that. I gonna try it as C programm later. \$\endgroup\$
    – Knerd
    Jun 6, 2014 at 23:12
0
\$\begingroup\$

Perl 33

$_=<>;$x+=ord for split'';print$x

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

\$\endgroup\$
1
  • \$\begingroup\$ Nice short answer. Think needs a chomp somewhere though, as gives 1095 as answer to Hello World! instead of 1085. \$\endgroup\$
    – steve
    Oct 7, 2015 at 17:46
0
\$\begingroup\$

Cobra - 81

class P
    def main
        c,d=Console.readLine,0
        for i in c,d+=i to int
        print d
\$\endgroup\$
0
\$\begingroup\$

C# in LINQPad, 28

Console.ReadLine().Sum(i=>i)
\$\endgroup\$
5
  • \$\begingroup\$ Will it execute as it is written? See the notes ;) \$\endgroup\$
    – Knerd
    Jun 5, 2014 at 20:07
  • \$\begingroup\$ Edited and fixed. \$\endgroup\$
    – Jacob
    Jun 5, 2014 at 20:24
  • \$\begingroup\$ Won't execute, you are missing the using System; part. \$\endgroup\$
    – Knerd
    Jun 5, 2014 at 20:37
  • \$\begingroup\$ 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. \$\endgroup\$
    – Jacob
    Jun 6, 2014 at 4:45
  • \$\begingroup\$ Yeah, should work. For the speed test I gonna add the environment stuff ;) \$\endgroup\$
    – Knerd
    Jun 6, 2014 at 7:06
0
\$\begingroup\$

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

Common Lisp, 35

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

Produces 3053 when given its own code.

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

><>, 19 bytes

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

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

Try it here

\$\endgroup\$
1
  • 3
    \$\begingroup\$ 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) \$\endgroup\$
    – cole
    Oct 9, 2015 at 3:39
0
\$\begingroup\$

Perl 22

s/./$t+=ord$&/eg;say$t

sample:

perl -nE 's/./$t+=ord$&/eg;say$t'  < <(echo -n Hello\ World\!)
1085
\$\endgroup\$
0
\$\begingroup\$

Perl, 34 32 27 25 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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – manatwork
    Oct 7, 2015 at 19:19
  • 1
    \$\begingroup\$ As both -n and -p cost the same 1 character, better use the later and replace print$a$_=$a. \$\endgroup\$
    – manatwork
    Oct 7, 2015 at 19:25
0
\$\begingroup\$

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

Mathematica, 19 bytes

Tr@*ToCharacterCode

Test case:

Tr@*ToCharacterCode@"Hello World!"
(* 1085 *)
\$\endgroup\$
0
\$\begingroup\$

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

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

Mathcad, 11 "bytes"

enter image description here

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

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

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

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.

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

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.

\$\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.