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

Mathcad, 13 "bytes"

enter image description here

Uses built-in vector summation operator and string-to-vectorOfCharacterCodes function. Definition operator ":=" entered by single key ":", summation operator by ctl-4.

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ FWIW: There's an useless whitespace before for. \$\endgroup\$
    – Yytsi
    Dec 24, 2016 at 11:13
0
\$\begingroup\$

Clojure, 31 bytes

#(reduce +(map int(read-line)))

Really straightforward. Gets its input from stdin, works with Unicode.

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

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

Pushy, 2 bytes

S#

Try it online!

Input is automatically converted to charcodes and placed on the stack. S sums the stack, and # prints it.

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

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)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ The counter overflows if you input something such as Hello World!... \$\endgroup\$
    – FlipTack
    Dec 24, 2016 at 11:08
0
\$\begingroup\$

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}{

Try it online!

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

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

C# (Visual C# Interactive Compiler), 14 bytes

s=>s.Sum(x=>x)

Try it online!

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

Ahead, 5 bytes

SK+O@

S      slurp input
 K+    reduce stack by summing
   O   output sum
    @  end

Try it online!

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

Kotlin, 22 bytes

(String) -> Int lambda.

{it.sumBy{it.toInt()}}

Try it online!

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

Japt -mx, 1 byte

c

Try it!


If the input cannot be an array of chars, then this can be done in 3 bytes:

¬xc

Try it!

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

Runic Enchantments, 10 bytes (Self-sum: 703)

iul1)?@+2?

Try it online!

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

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

@, 4 bytes

Seems like a perfect task for @.

Σš

Explanation

Σ  Summation of
 š a one-line input
\$\endgroup\$
0
\$\begingroup\$

Brain-Flak, 6 bytes (own code sum: 577)

({{}})

Try it online!

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

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.

Sinclair ZX80 Calculator that adds char values

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

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

Try it online!

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

𝔼𝕊𝕄𝕚𝕟 2, 5 chars / 13 bytes

⨭ ᴉ⒨⒞

Try it here (Firefox only).

Splits and maps the input to its charcodes, then sums the resulting array.

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

Pyth, 3 bytes

sCM

Try it online!

Alternatively, smC works as well.

Explanation:

    # implicit output
s   # sum(                )
  M #     map(   ,       )
 C  #         ord
    #             input()   -> implicit input
\$\endgroup\$
0
\$\begingroup\$

K (ngn/k), 2 bytes

+/

Try it online!

In K, a string is basically a list of ASCII char codes, so just the sum adverb will do the job.

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

Go, 58 bytes

func f(b[]byte)(s int){for _,e:=range b{s+=int(e)}
return}

Attempt This Online!

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

Raku, 10 bytes

*.ords.sum

Try it online!

The ords string method conveniently returns a list of the ordinal values of the characters.

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

Thunno 2 SB, 0 bytes

Attempt This Online!

Or, 2 bytes flagless:

CS

Attempt This Online!

\$\endgroup\$
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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