| Bytes | Lang | Time | Link |
|---|---|---|---|
| 059 | Tcl | 250227T162841Z | sergiol |
| 006 | Coreutils sum | 240620T060141Z | roblogic |
| 003 | Japt | 240619T223222Z | Shaggy |
| 017 | ><> | 240619T133238Z | Evylah |
| 054 | Google Sheets | 240613T214222Z | Glory2Uk |
| 000 | Thunno 2 SB | 230608T183713Z | The Thon |
| nan | Fig | 221011T195812Z | naffetS |
| 010 | Raku | 221011T195522Z | Sean |
| 058 | Go | 221011T155413Z | bigyihsu |
| 002 | K ngn/k | 221011T093734Z | oeuf |
| 003 | Pyth | 221011T072556Z | u-ndefin |
| 002 | Vyxal | 221011T064929Z | DialFros |
| 513 | 𝔼𝕊𝕄𝕚𝕟 2 | 160106T010804Z | Mama Fun |
| 002 | PlatyPar | 160106T003339Z | Cyoce |
| 079 | Java 8 | 160102T144832Z | The Code |
| 002 | Jolf | 160104T013524Z | Conor O& |
| 077 | JavaScript function golf | 160106T113514Z | user4853 |
| 004 | Gol><> | 160102T160246Z | randomra |
| 006 | Japt | 160104T030623Z | ETHprodu |
| 002 | W | 191130T103247Z | user8505 |
| 002 | Keg | 190902T125313Z | user8505 |
| 035 | Wren | 191130T113126Z | user8505 |
| 065 | Unexpended Sinclair ZX80 65 tokenized BASIC bytes | 190619T150440Z | Shaun Be |
| 6577 | BrainFlak | 190902T131439Z | Dorian |
| 004 | @ | 190902T124540Z | user8505 |
| nan | Runic Enchantments | 190619T231946Z | Draco18s |
| 046 | PHP | 190620T150413Z | 640KB |
| 001 | Japt mx | 190620T134545Z | Oliver |
| 022 | Kotlin | 190619T175159Z | snail_ |
| 005 | Ahead | 190619T174222Z | snail_ |
| 014 | C# Visual C# Interactive Compiler | 190619T100701Z | Innat3 |
| 061 | Whitespace | 190619T064248Z | Kevin Cr |
| 002 | 05AB1E | 190619T063036Z | Kevin Cr |
| 015 | Perl 5 pF | 190619T053506Z | Xcali |
| 012 | Ruby | 140605T142855Z | Doorknob |
| 4236 | SML | 140607T005620Z | someonr |
| 006 | Minkolang | 161224T104921Z | user4180 |
| 015 | Brainfuck 15 Bytes | 161224T104911Z | FinW |
| 002 | Pushy | 161224T104812Z | FlipTack |
| 024 | Python | 161224T104558Z | FlipTack |
| 010 | Cubix | 161224T102811Z | ETHprodu |
| 037 | JavaScript ES6 | 161224T100501Z | ETHprodu |
| 018 | Hoon | 160523T160038Z | RenderSe |
| 031 | Clojure | 160523T152926Z | cliffroo |
| 037 | Python 3 | 160521T151741Z | m654 |
| 008 | Unipants' Golfing Language | 160420T160047Z | user4853 |
| 013 | Mathcad | 160422T085859Z | Stuart B |
| 113 | Java 8 | 160421T223511Z | Khaled.K |
| 003 | Factor | 160422T023228Z | cat |
| 139 | Java | 160421T223957Z | Ashwin G |
| 131 | C++ | 160421T205949Z | Michelfr |
| 011 | Mathcad | 160420T161443Z | Stuart B |
| 012 | jq | 151007T162425Z | manatwor |
| 041 | Javascript ES6 | 151009T030247Z | Mama Fun |
| 3260 | CJam | 140606T165149Z | aditsu q |
| 019 | Mathematica | 160104T021754Z | njpipeor |
| nan | Java | 160102T134705Z | SuperJed |
| 059 | Go | 140606T060915Z | voutasau |
| nan | Perl | 151007T190217Z | steve |
| 001 | gs2 | 151007T192154Z | lynn |
| 022 | Perl | 151007T191942Z | F. Hauri |
| 004 | Matlab/Octave | 151007T172129Z | flawr |
| 019 | ><> | 151007T171356Z | DanTheMa |
| 035 | Common Lisp | 151007T151439Z | coredump |
| 002 | K5 | 151007T141131Z | kirbyfan |
| nan | R | 140606T143444Z | plannapu |
| 041 | 8086 Assembly 16bit | 140618T233328Z | anatolyg |
| 006 | Befunge98 | 140605T212210Z | alephrei |
| 007 | J | 140605T150231Z | ɐɔıʇǝɥʇu |
| 008 | k | 140607T161628Z | skeevey |
| 051 | Javascript ES6 | 140607T062012Z | nderscor |
| nan | Julia 11 7 characters | 140606T043058Z | Glen O |
| 029 | Shell+GNU tools | 140605T175302Z | Digital |
| 027 | PowerShell | 140606T152041Z | Rynant |
| 083 | Delphi | 140606T145350Z | Teun Pro |
| 009 | J | 140606T142242Z | Dan Bron |
| nan | 140605T164531Z | core1024 | |
| 028 | C# in LINQPad | 140605T193132Z | Jacob |
| 081 | Cobra | 140606T041013Z | Οurous |
| 033 | Perl | 140605T214402Z | SL2 |
| 063 | C | 140605T204329Z | Abhijit |
| 060 | D function | 140605T175326Z | Hugo Dub |
| 036 | Haskell | 140605T144505Z | gxtaillo |
| 032 | C | 140605T174224Z | bebe |
| 004 | GolfScript | 140605T143137Z | Doorknob |
| 028 | Python 3 | 140605T143145Z | undergro |
| 057 | Lua | 140605T143643Z | Kyle Kan |
| 008 | APL | 140605T142846Z | marinus |
Coreutils sum, 8 6 bytes
Gnu Coreutils sum, (obsolescent but remains available for compatibility) takes an input stream or a file. The -s flag invokes old System V logic, which just adds up the byte values.
sum -s
Try it online! 8 bytes
Notes:
* sum defaults to the BSD checksum algorithm which is also obsolescent
* Bonus score: 533⭐️
* related q:258739
><>, 17 bytes
0i:0(?v+!
;n~<
basically my first answer I thought of, I couldn't think of ways to optimize this further.
Google Sheets, 59 54 bytes
=SUM(ARRAYFORMULA(code(mid(A1,SEQUENCE(len(A1)),1))))
A cell formula based on the array reduction: the character codes are accumulated and the end sum is output
Below is the old 59 byte version:
=REDUCE(,SEQUENCE(LEN(A1)),LAMBDA(a,b,a+CODE(MID(A1,b,1))))
.
Raku, 10 bytes
*.ords.sum
The ords string method conveniently returns a list of the ordinal values of the characters.
K (ngn/k), 2 bytes
+/
In K, a string is basically a list of ASCII char codes, so just the sum adverb will do the job.
Pyth, 3 bytes
sCM
Alternatively, smC works as well.
Explanation:
# implicit output
s # sum( )
M # map( , )
C # ord
# input() -> implicit input
𝔼𝕊𝕄𝕚𝕟 2, 5 chars / 13 bytes
⨭ ᴉ⒨⒞
Splits and maps the input to its charcodes, then sums the resulting array.
PlatyPar, 2 bytes
us
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).
Java 8 - 79 bytes
interface C{static void main(String[]a){System.out.print(a[0].chars().sum());}}
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
Gol><>, 4 bytes
iEh+
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
Keg, 2 bytes
?⅀
Explanation
? # Read the full input string
⅀ # Sum the whole stack
# Implicit output
Wren, 35 bytes
The fact that they aren't doing this in Wren is a perfect chance for me.
Fn.new{|x|x.bytes.reduce{|a,i|a+i}}
Explanation
Fn.new{|x| } // New anonymous function with parameter x
x.bytes // Convert x to its bytecode forms
.reduce{|a,i|a+i} // Sum this bytecode form
Unexpended Sinclair ZX80 - 65 tokenized BASIC bytes
1 INPUT A$
2 LET A=0
3 IF A$="" THEN GO TO 7
4 LET A=A+CODE(A$)
5 LET A$=TL$(A$)
6 GO TO 3
7 PRINT A
There are a few caveats, without POKEing some (or one, I don't recall) memory location(s), all maths is done via 16-bit signed integers, so the range is -32768 to +32767, so any string entered that is too long will overflow the VAR stack and break the program. Also, the ZX80 character set is not ASCII compatible and there is no exclamation mark, so HELLO WORLD (as there are no lower-case characters by default either) is 494 - source.
BASIC does not update the screen whilst doing calculations and such, so after entering the string it will take some time to work out where nothing will be displayed. Your original string entered in the A$ variable will not show.
Brain-Flak, 6 bytes (own code sum: 577)
({{}})
Seems to be a good challenge for Brain-Flak.
Explanation:
{ } while top of Stack is not 0, calculate sum of
{} pop value
( ) push calculated sum
implicitly output the Stack
Runic Enchantments, 10 bytes (Self-sum: 703)
iul1)?@+2?
It has a limit on how long of a string it can handle. For a version that can handle any length string:
/l͍:i0< /~~@
R1-:0≮?/:}}:{%3s}+}
Try it online! (Self-sum: 3937)
In both cases spaces need to be escaped in order to be read as a single input. The first one works by unconcatening the string and iteratively adding each character together until only a single value is left (printing it).
The second uses an index pointer and extracts one character at a time, adding it to a running total (requiring more in the way of setup and stack manipulation).
PHP, 46 bytes
No PHP answer on this yet, so here's the easy one:
<?=array_sum(array_map(ord,str_split($argn)));
$ 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;
51 bytes
Iterative 2:
while($i<strlen($argn))$x+=ord($argn[$i++]);echo$x;
63 bytes
Recursive:
function f($s,$c=0){return$s?f(substr($s,1),ord($s[0])+$c):$c;}
69 bytes
Using PHP's rarely used [citation needed] array_reduce() function:
<?=array_reduce(str_split($argn),function($c,$i){return$c+ord($i);});
Whitespace, 61 bytes
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_top][S N
S _Duplicate_top][T N
T S _Read_STDIN_as_character][T T T _Retrieve_input][S N
S _Duplicate][S S S T S T S N
_Push_10][T S S T _Subtract][N
T S S N
_If_0_Jump_to_Label_PRINT][T S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_newline][T N
S T _Output_top_as_integer]
Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Since Whitespace inputs one character at a time, the input should contain a trailing newline so it knows when to stop reading characters and the input is done.
Try it online (with raw spaces, tabs, and new-lines only).
Explanation in pseudo-code:
Integer s = 0
Start LOOP:
Integer c = Read STDIN as character
If(c == 10) // c == '\n'
Call function PRINT
s = s + c
Go to next iteration of LOOP
function PRINT:
Discard the top of the stack (the 10 / newline)
Print s as integer to STDOUT
05AB1E, 2 bytes
ÇO
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)
Perl 5 -pF, 15 bytes
Under the rules in place at the time of this challenge, I believe it would have been +3 for the command line flags, giving a score of 18.
map$\+=ord,@F}{
Ruby, 13 12 bytes
p~9+gets.sum
sum is a built-in function that sums the characters of a string. Subtracts 10 to account for the newline at the end of gets's return value.
(Edited 4 years later to change x-10 to ~9+x... the value of ~9 is -10, but it lets us remove the space between p and its argument, saving a byte.)
SML, 42 36
Just adding another language.
fun$x=foldl op+0(map ord(explode x))
Converts String to char array, calculates ascii number of each value and calculates the sum of all ascii numbers.
Minkolang, 6 bytes
$o$+N.
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
Brainfuck - 15 Bytes
,[>,]<[[<+>-]<]
Try it here (You have to click the box marked "!")
Put your input after the exclamation point. (not necessary but allows easy EOF.)
What it does
,[>,] take input as characters in separate cells until input has ended (automatically in ascii)
< go to the last character
[ infinite loop
[<+>-] add the last character and the character before it and save it as the last character
<] go back to the last character and then do the infinite loop again
Unfortunately, it exits with an out of memory error and does not print the output, but that wasn't part of the challenge. If you want to see the output, read the tape. It also only goes up to 255 on this interpreter. (if anyone knows an interpreter with larger cells that exits on error, that would be great)
Pushy, 2 bytes
S#
Input is automatically converted to charcodes and placed on the stack. S sums the stack, and # prints it.
Python, 24 bytes
This is shorter than any Python solution so far: an unnamed anonymous function, which takes the string as an argument, and returns the sum.
lambda x:sum(x.encode())
First, x.encode() transforms it into a bytes object. Then, sum adds the char-code values. As this is a lambda function, the value is implicity returned.
Additionally, one could have lambda x:sum(map(ord,x)) for the same byte count.
Cubix, 10 bytes
OU@;i)!^(+
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.
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.
Hoon, 18 bytes
|*
*
(roll +< add)
This is a wet gate, so that I don't have to specify tape instead of *. This has the added bonus of it being fully generic, so it could actually accept (list @ud) too. Wet gates typecheck at the call site, instead of definition.
+< is the sample of the gate, indexed into the sample with tree navigation syntax because it's shorter than naming the function arguments. |*(a/* a) is longer than |*(* +<).
> %. "Hello World!"
|*
*
(roll +< add)
b=1.085
Unfortunately, this doesn't work correctly as-is with unicode. Urbit's string literals are lists of UTF8 chars. You can use ++tuba to convert it to UTF32, though.
> %. "⚳ℚ⊻"
|*
*
(roll +< add)
b=1.622
> %. (tuba "⚳ℚ⊻")
|*
*
(roll +< add)
b=27.272
Clojure, 31 bytes
#(reduce +(map int(read-line)))
Really straightforward. Gets its input from stdin, works with Unicode.
Python 3, 37 bytes
print(sum([ord(c) for c in input()]))
There's a shorter one, but this is possible as well. It converts the string into a list will all the ASCII values of the characters and adds them together using sum().
Star version, 55 bytes
a=sum([ord(c) for c in input()]);print(a);print(chr(a))
Now gimme my gold star.
Unipants' Golfing Language, 8 bytes
cIl+I:_o
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.
Mathcad, 13 "bytes"
Uses built-in vector summation operator and string-to-vectorOfCharacterCodes function. Definition operator ":=" entered by single key ":", summation operator by ctl-4.
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;
s.chars().forEach(x -> i = i.add(BigInteger.valueOf(x));
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
}
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.
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.
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;
}
Mathcad, 11 "bytes"
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).
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.)
Javascript ES6, 41 bytes
_=>[..._].map(y=>x+=y.charCodeAt(),x=0)|x
Thanks to @ETHproductions for 2 bytes saved!
CJam, 3 bytes (sum 260)
q1b
You can try it online.
Thanks jimmy23013 for helping chop off 2 characters :)
Explanation:
q read the input into a string
1b convert from base 1, treating each character as its numeric value
Mathematica, 19 bytes
Tr@*ToCharacterCode
Test case:
Tr@*ToCharacterCode@"Hello World!"
(* 1085 *)
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);}}
Go (59 characters)
func d(s string)(t int){for _,x:=range s{t+=int(x)};return}
Everything in Go is utf8 by default. Codetext in ` delimeters run through itself gives an output of: 5399.
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
Perl 22
s/./$t+=ord$&/eg;say$t
sample:
perl -nE 's/./$t+=ord$&/eg;say$t' < <(echo -n Hello\ World\!)
1085
Matlab/Octave 4 bytes (bonus: 405)
This code is an anonymous function, that does the job, it will take a string, and return the required number.
@sum
><>, 19 bytes
0i:1+?!v+!
;n~<
It does work on Unicode. For example, this correctly outputs 27272
: ⚳ℚ⊻
Common Lisp, 35
(reduce'+(read-line):key'char-code)
Produces 3053 when given its own code.
K5, 2 bytes (function), 5 bytes (program)
Function
+/
Program
+/0:`
Not sure if K5 was created before or after this challenge was posted. Regardless...THIS IS AWESOME!!
In K5, if you perform arithmetic operations on strings, it converts the characters to their ASCII codes. So this just uses the sum operator +/ (actually, it's plus + over).
R, 35 characters (sum of 3086) 26 bytes (sum of 2305)
sum(utf8ToInt(readline()))
readline() is one character longer than scan(,"") but scan split the input on spaces by default.
Usage:
> sum(utf8ToInt(readline()))
Hello World!
[1] 1085
> sum(utf8ToInt(readline()))
sum(utf8ToInt(readline()))
[1] 2305
> sum(utf8ToInt(readline()))
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!(
[1] 14835
8086 Assembly (16-bit) - 47 41 bytes
The contents of the test.com file are:
98 01 c3 b4 01 cd 21 3c 0d 75 f5 89 c7 c6 05 24
89 d8 b1 0a 4f 31 d2 f7 f1 80 ca 30 88 15 09 c0
75 f2 89 fa b4 09 cd 21 c3
Actual work is done in the first 11 bytes; I need the rest to print the result in decimal notation.
Source code (give as input to the DOS debug.com assembler):
a
; input the string; count the sum
cbw
add bx, ax
mov ah, 1
int 21
cmp al, d
jne 100
; Prepare for output: stuff an end-of-line marker
mov di, ax
mov [di], byte 24
mov ax, bx
mov cl, a
; 114
; Divide by 10; write digits to buffer
dec di
xor dx, dx
div cx
or dl, 30
mov [di], dl
or ax, ax
jne 114
; Print the string
mov dx, di
mov ah, 9
int 21
ret
rcx 29
n test.com
w
q
Some notes on the code:
- Only handles one line (up to end-of-line character 13); hangs if no end-of-line
- Only 7-bit characters are supported (results are incorrect otherwise)
- Outputs 0 for empty input
- Cannot handle output greater than 64K
- Instruction at address 0x10d overwrites itself (pure coincidence)
- Have to use DOS emulators like DosBox to assemble and run this program
Befunge98, 6 bytes, sum: 445
2j@.~+
Any interpreter should be fine. I use CCBI.
Use as follows:
printf 'Hello World!' | ccbi calc.fg
Works for multibyte chars and empty strings.
Explanation
2j- jump over the next two instructions (@and.- see below)~- put the next char on the stack+- add the code value of the new char to the current sum. The instruction pointer wraps to the beginning and the cycle repeats- when
~encounters an EOF it inverses the direction of the pointer and the two "hidden" instructions are executed: .- print the sum@- exit
J (7)
So close, yet so far... Oh well, I guess 7 is decent enough, since this answer also accepts empty strings. (I'm basing my usage of a variable as input on the phrase from a file, stdin or whatever)
+/a.i.b
Explanation:
a.
┌┬┐├┼┤└┴┘│─ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~��������������������������������������������������������������������������������������������������������������������������������
a. contains all ASCII chars.
'people' i. 'pow'
0 2 6
x i. y is similar to python's [x.index(i) for i in y].
a. i. 'Hello World!'
72 101 108 108 111 32 87 111 114 108 100 33
Therefor, a. i. y converts y to an array of its ASCII values
+/1 2 3 4 5 6
21
+/ is like sum: +/1 2 3 4 5 6 means 1+2+3+4+5+6
+/ a. i. 'Hello World!'
1085
The whole thing in action
For the bonus:
b=:'+/a.i.b'
+/a.i.b
482
Not bad, I guess.
b=:'0\{+}/'
+/a.i.b
478
Well, darn.
A=:'+/a.i.A'
+/a.i.A
449
Thanks @algorithmshark
A=:'+/3 u:A'
+/3 u:A
413
Thanks @marinus
k (8 chars)
+/6h$0:0
Q translation
sum `int$read0 0
Bonus value:
k)+/6h$0:0
+/6h$0:0
438i
Javascript (ES6) 51
alert([...prompt(x=0)].map(y=>x+=y.charCodeAt())|x)
Julia - 11 7 characters, resultant sum = 943 536
Since the question allows the input to come from whatever source you want, I choose an existing variable. Assume that A contains the string we wish to evaluate.
sum(A)1
As it turns out, you can sum the string directly, and it will evaluate... however, due to the way that summing of chars is handled, if there is an odd number of characters in the string, it will output a character, rather than an integer of any sort. As such, we force it to cast to int by multiplying by 1.
Old version:
sum(A.data)
Will output in a hexadecimal notation (if the sum is less than 256, it'll be 0x??, otherwise it'll be 8 byte as 0x????????). If used in code where the result is used, it will operate just like any other number (it's just how Julia displays unsigned ints).
To see the value of the result in decimal, enclose the above in int(), as in int(sum(A.data)).
For anybody who doesn't know Julia, you assign to A exactly the same way you do other assignments to variables. So, A="Hello World!" or A="sum(n.data)". In the case where you need to put in " or ' characters, there are multiple options, the easiest of which (because it avoids need for knowledge of the nuances of Julia string literals) is A=readline(), followed by simply typing in the string into STDIN (won't handle newlines, though). The escape sequence for newline is, as usual, \n, but I don't believe you can use that with readline().
Shell+GNU tools, 29 bytes
echo `od -An -tuC`|tr \ +|bc
Takes input from stdin:
$ printf "%s" 'Hello World!' | ./addchars.sh
1085
$
Own score: 2385
c, 52 bytes
c;main(p){while(~(p=getchar()))c+=p;printf("%d",c);}
Compile with (some warnings produced):
gcc addchars.c -o addchars
Takes input from stdin:
$ printf "%s" 'Hello World!' | ./addchars
1085 $
Own score: 4354
PowerShell - 27
[char[]]$args[0]|measure -s
Example
> SumChars.ps1 'Hello World!'
Count : 12
Average :
Sum : 1085
Maximum :
Minimum :
Property :
Delphi (87 83)
function x(s:string):int64;var c:char;begin x:=0;for c in s do x:=result+ord(c)end;
Ungolfed
function x(s:string):int64;
var
c:char;
begin
x:=0;
for c in s do
x:=result+ord(c)
end;
Loops through S adding the ord value of the char to the result. where x==result
Edits:
Saved 4 characters by switching to int64 and changing the adding to the sum.
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
JavaScript (ES6) 54 58
alert([].reduce.call(prompt(),(v,c)=>v+c.charCodeAt(0),0))
54 bytes thanks to nderscore:
alert([...prompt()].reduce((v,c)=>v+c.charCodeAt(),0))
C# in LINQPad, 28
Console.ReadLine().Sum(i=>i)
Cobra - 81
class P
def main
c,d=Console.readLine,0
for i in c,d+=i to int
print d
Perl 33
$_=<>;$x+=ord for split'';print$x
I don't know Perl too well. I'm sure it can be golfed some more.
C 63
main(a,b)char**b;{a+=*b[1];*b[1]++?main(a,b):printf("%d",a-2);}
D (function: 60)
Definitely not in it to win it.
Assuming it doesn't need to be a complete program
int c(string i){int s;foreach(e;i){s+=cast(int)e;}return s;}
Called like so
void main ()
{
import std.stdio;
auto hw = "Hello World!";
writefln("%s = %d", hw, c(hw));
}
Output:
Hello World! = 1085
D (program: 133)
Does not count line breaks.
void main(){import std.algorithm,std.stdio;stdin.byLine.map!((a){int s;foreach(e;a){s+=cast(int)e;}return s;}).reduce!"a+b".writeln;}
With more whitespace and longer variable names for readability
void main () {
import std.algorithm, std.stdio;
stdin.byLine
.map!((line) {
int sum;
foreach (ch; line) {
sum += cast(int)ch;
}
return sum;
})
.reduce!"a+b"
.writeln;
}
To support line breaks in the input, I could either use byLine(KeepTerminator.yes) — the correct way, for 20 characters — or append a '\n' to my line — which breaks single-line input and may give the wrong sum on Windows because of CRLF, for 18 characters.
Haskell 36
main=interact$show.sum.map fromEnum
C 32
f(char*s){return*s?*s+f(s+1):0;}
GolfScript, 4 characters
{+}*
Simply uses the fold operator (*) to add up all the characters.
If it has to work with the empty string, 9 chars:
{{+}*}0if
Thanks to @PeterTaylor for providing an alternative 6-char version that works with empty string:
0\{+}/
Python 3 - 28 bytes
print(sum(map(ord,input())))
Example run:
$ ./sum_string.py <<< 'Hello World!'
1085
Gets input from stdin, maps the ord function to it to get the ASCII value of each character, sums it and prints.
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.
APL (8)
+/⎕UCS⍞
Explanation:
+/sum of⎕UCSunicode values of⍞character input


