31
\$\begingroup\$

Consider a stream/file with one integer per line. For example:

123
5
99

Your code should output the sum of these numbers, that is 227.

The input format is strictly one integer per line. You cannot, for example, assume the input is on one line as an array of integers.

You can take input either from STDIN, in form of a filename, or a file with a name of your choice; you can choose which one. No other ways of getting input are allowed.

The input will contain at least one integer. You can assume all integers are non-negative and that their total sum is less than 232.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ Is there a trailing newline? Is that newline optional? \$\endgroup\$ Mar 24, 2017 at 6:50
  • 9
    \$\begingroup\$ Hi! I downvoted this challenge because it goes against our community standards for acceptable input/output formats by having a restrictive input format. \$\endgroup\$ Mar 24, 2017 at 15:34
  • 1
    \$\begingroup\$ @AdmBorkBork and I discussed this at length in the chat room. We have agreed to disagree :) \$\endgroup\$
    – user9206
    Mar 24, 2017 at 17:09
  • 23
    \$\begingroup\$ As the author of the things-to-avoid of cumbersome I/O and arbitrarily overriding defaults, I want to defend this challenge on those grounds. Here, the processing input is the meat of the challenge, not extra work that distracts from the main challenge. It's not "add numbers" with weird I/O requirements, it's "do this I/O" with adding as a step. Overruling the standard I/O is necessary for answers not to shortcut across the main task. \$\endgroup\$
    – xnor
    Mar 24, 2017 at 18:58
  • 2
    \$\begingroup\$ Why can't function input be used? \$\endgroup\$ Apr 9, 2017 at 21:02

76 Answers 76

22
\$\begingroup\$

Bash + coreutils, 16 bytes

xargs|tr \  +|bc

Try it online!

There are two spaces after the \. This works for negative numbers as well.

Explanation:

xargs             # known trick to turn newlines into spaces, while adding a
                  #trailing newline when printing the result (needed for bc)
|tr \  +          # turn spaces into '+'s
|bc               # calculates the sum

You may wonder why tr \\n +|bc isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors:

  • if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition
  • and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s.
\$\endgroup\$
10
  • 1
    \$\begingroup\$ I like this. It's nice and clever. \$\endgroup\$
    – user9206
    Mar 23, 2017 at 21:04
  • \$\begingroup\$ Could you use tr \\n + Instead without xargs? \$\endgroup\$
    – user9206
    Mar 23, 2017 at 23:03
  • 1
    \$\begingroup\$ @Lembik Do you mean tr \\n +|bc? If so, then please see the updated explanation. Good question. \$\endgroup\$
    – seshoumara
    Mar 24, 2017 at 0:50
  • \$\begingroup\$ paste -s -d+|bc is 15 bytes \$\endgroup\$ Mar 24, 2017 at 13:29
  • 1
    \$\begingroup\$ @Lembik Didn't considered that case, but fortunately the script still works. xargs|tr \ + in this case does nothing, and bc receives the number and prints it back. \$\endgroup\$
    – seshoumara
    Mar 24, 2017 at 15:36
15
\$\begingroup\$

05AB1E, 2 bytes

|O

Explanation:

|   Get input as array
 O  Sum

Try it online!

\$\endgroup\$
7
  • 7
    \$\begingroup\$ That's ridiculous :) \$\endgroup\$
    – user9206
    Mar 23, 2017 at 20:41
  • \$\begingroup\$ Does this read from standard in? \$\endgroup\$
    – user9206
    Mar 23, 2017 at 20:50
  • 1
    \$\begingroup\$ @Lembik it does. \$\endgroup\$
    – Okx
    Mar 24, 2017 at 8:38
  • \$\begingroup\$ I believe your 2 byte answer was first. You are the winner! (Unless someone finds a 1 byte answer.) \$\endgroup\$
    – user9206
    Mar 24, 2017 at 13:38
  • 4
    \$\begingroup\$ @Lembik Or a 0 byte answer.... \$\endgroup\$
    – sporklpony
    Mar 24, 2017 at 15:29
14
\$\begingroup\$

MATL, 2 bytes

Us

This expects the input in a text file called defin.

Gif or it didn't happen:

enter image description here

Or try it online! (thanks to Dennis for the set-up!)

Explanation

When a MATL program is run, if a file called defin is found (the name refers to "default input"), its contents are automatically loaded as text and pushed to the stack as a string before executing the code.

Function U evaluates the string to convert it to a column vector of numbers, and s computes the sum, which is implicitly displayed.

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

Japt, 2 bytes

Nx

Explanation

     Implicit: parse STDIN into array of numbers, strings, and arrays
N    Get the resulting parsed array.
 x   Sum.
     Implicit: output result of last expression

Try it online!

\$\endgroup\$
12
\$\begingroup\$

Paste + bc, 13 bytes

paste -sd+|bc

Explanation:

paste -s        Take one line at a time from input
        d+      Joining by '+'
          |bc   Pass as expression to bc

Another shell answer!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Very neat and tidy. \$\endgroup\$
    – user9206
    Mar 23, 2017 at 21:05
  • \$\begingroup\$ Ooh, I had paste -s -d+|bc and didn't realize I could consolidate the switches. Neat! \$\endgroup\$ Mar 24, 2017 at 13:31
12
\$\begingroup\$

Perl 6, 13 bytes

say sum lines

Try it

Explanation

  • lines() returns a list of lines from $*IN or $*ARGFILES a “magic” command-line input handle.
  • sum(…) was added to Perl 6 to allow [+] List to be optimized for Positionals that can calculate their sum without generating all of their values like 1..100000
    (I just thought sum was just too cute here to use [+] like I normally would)
  • say(…) call the .gist method on its input, and prints it with an additional newline.
\$\endgroup\$
6
  • \$\begingroup\$ What is it perl 5? \$\endgroup\$
    – user9206
    Mar 23, 2017 at 21:02
  • 15
    \$\begingroup\$ this reads like lolcode \$\endgroup\$ Mar 23, 2017 at 21:58
  • \$\begingroup\$ @Lembik it is clearly labeled as Perl 6, which is a sister language to Perl 5. \$\endgroup\$ Mar 23, 2017 at 22:00
  • \$\begingroup\$ There was a typo. I meant what is it in Perl 5? \$\endgroup\$
    – user9206
    Mar 23, 2017 at 22:10
  • 1
    \$\begingroup\$ Well $a+=$_ for <>;print $a works in Perl 5, but there may be a shorter way. \$\endgroup\$ Mar 23, 2017 at 22:14
10
\$\begingroup\$

C, 53 bytes

r;main(i){for(;~scanf("%d",&i);r+=i);printf("%d",r);}
\$\endgroup\$
2
  • \$\begingroup\$ C showing its credentials again :) \$\endgroup\$
    – user9206
    Mar 23, 2017 at 21:04
  • 2
    \$\begingroup\$ I feel like there should be a shorter way, but I don't see it :) \$\endgroup\$ Mar 25, 2017 at 1:41
9
\$\begingroup\$

Python 3, 28 bytes

print(sum(map(int,open(0))))

Taken from this tip. I've been told this won't work on Windows.

Try it online!

\$\endgroup\$
1
  • 5
    \$\begingroup\$ I learned something new! \$\endgroup\$
    – user9206
    Mar 23, 2017 at 22:18
9
\$\begingroup\$

Retina, 11 7 bytes

-4 thanks to Martin Ender

.*
$*
1

Try it online!


Convert to unary:

.*
$*

Count the number of 1s:

1
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Interesting how Retina, as a regex based language, can do the sum in fewer bytes than the shortest bash answer posted so far. +1 \$\endgroup\$
    – seshoumara
    Mar 23, 2017 at 21:56
  • \$\begingroup\$ Is this reading from standard in? \$\endgroup\$
    – user9206
    Mar 23, 2017 at 22:34
  • 2
    \$\begingroup\$ @Lembik Yes it is. \$\endgroup\$
    – Riley
    Mar 23, 2017 at 22:38
  • \$\begingroup\$ If input in unary was allowed, it'd be only one byte. \$\endgroup\$
    – mbomb007
    Mar 24, 2017 at 14:06
  • \$\begingroup\$ @mbomb007 I already tried that in sed. \$\endgroup\$
    – Riley
    Mar 24, 2017 at 14:07
8
\$\begingroup\$

Brain-Flak, 20 bytes

(([]){[{}]{}([])}{})

Try it online!

Explanation

This is a golf off of a solution made by Riley in chat. His solution was:

([])({<{}>{}<([])>}{})

If your familiar with Brain-Flak this is pretty self-explanatory. It pushes the stack height and pops one value as it counts down, at the end it pushes the sum of all the runs.

It is a pretty good golf but he zeros both {} and ([]) however these will have a values that only differ by one so if instead we remove the masks and make one of the two negative they should nearly cancel out.

([])({[{}]{}([])}{})

Since they always differ by one we have the unfortunate circumstance where our answer is always off by the stack height. In order to remedy this we simply move the beginning of the push to encompass the first stack height.

(([]){[{}]{}([])}{})
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I thought of it as the negative pop cancels the previous height pushed (from before the loop, or the end of the previous time through), and the last height is 0 so it can be ignored. \$\endgroup\$
    – Riley
    Mar 23, 2017 at 20:51
8
\$\begingroup\$

Python 2, 40 bytes

import sys;print sum(map(int,sys.stdin))
\$\endgroup\$
8
\$\begingroup\$

Perl 5, 9 bytes

8 bytes of code + -p flag.

$\+=$_}{

Try it online!

With -p, the input is read one line at a time, stored in $_ each time. We use $\ as accumulator, because thanks to -p flag, it's implicitly printed at the end. The unmatched }{ are used so -p flag only prints $\ once at the end instead of printing $_ and $\ at each line it reads like it normally does.

\$\endgroup\$
6
  • \$\begingroup\$ I can't even parse it! :) Explanation please. \$\endgroup\$
    – user9206
    Mar 24, 2017 at 8:23
  • \$\begingroup\$ @Lembik Here you go. \$\endgroup\$
    – Dada
    Mar 24, 2017 at 8:28
  • \$\begingroup\$ The unmatched parenthesise part is very obscure! \$\endgroup\$
    – user9206
    Mar 24, 2017 at 8:31
  • \$\begingroup\$ @Lembik Those aren't parenthesizes... They're either French or Curly Braces depends on who you ask, but they definitely are not )( \$\endgroup\$
    – CraigR8806
    Mar 24, 2017 at 14:25
  • 1
    \$\begingroup\$ @Lembik accolades, apparently. \$\endgroup\$ Mar 27, 2017 at 9:40
7
\$\begingroup\$

R,11 bytes

sum(scan())

scan takes the input, one number per line. And sum, well, sums.

\$\endgroup\$
7
\$\begingroup\$

Pure Bash, 37 36 bytes

Thanks to @KevinCruijssen for a byte!

while read a;do((b+=a));done;echo $b

Try it online!

\$\endgroup\$
3
  • 3
    \$\begingroup\$ Very nice and clean. \$\endgroup\$
    – user9206
    Mar 23, 2017 at 21:03
  • \$\begingroup\$ I never program in Bash, but isn't it possible to remove the space between do ((? The TIO seems to work. \$\endgroup\$ Mar 24, 2017 at 8:42
  • \$\begingroup\$ @KevinCruijssen Yeah, it seems like it works. I use zsh as my daily shell and it doesn't work in zsh without a space, I just assumed it wouldn't work in Bash but apparently it does. \$\endgroup\$
    – betseg
    Mar 24, 2017 at 9:25
6
\$\begingroup\$

Haskell, 32 bytes

interact$show.sum.map read.lines

Try it online!.

interact collects the whole input from stdin, passes it to the function given as its argument and prints the string it gets back from this function. The function is:

            lines   -- split input into list of lines at nl
      map read      -- convert every line to a number (read is polymorphic,
                    -- but as want to sum it later, the type checker knows
                    -- it has to be numbers)
    sum             -- sum the list of numbers
show                -- convert back to string
\$\endgroup\$
1
  • 1
    \$\begingroup\$ This makes me really like Haskell. In Scala, I have to do lines.map(_.toInt) because sum expects some sort of numeric implicit conversion from String or in this case an explicit one. \$\endgroup\$ Mar 24, 2017 at 14:52
6
\$\begingroup\$

PHP, 22 bytes

<?=array_sum(file(t));

This assumes there is a file named "t" with a list of integers.

file() opens a file and returns an array with each line stored a separate element in the array. array_sum() sums all the elements in an array.

\$\endgroup\$
5
\$\begingroup\$

Awk, 19 bytes

{s+=$1}END{print s}

Explanation:

{s+=$1}                For all lines in the input, add to s
        END             End loop
           {print s}    Print s
\$\endgroup\$
2
  • 1
    \$\begingroup\$ "Explanation coming soon™" That'd be my new catchphrase if it weren't trademarked... \$\endgroup\$ Mar 23, 2017 at 20:55
  • 2
    \$\begingroup\$ In the language of awk, your answer is actually only 19 bytes: {s+=$1}END{print s} :) \$\endgroup\$ Mar 25, 2017 at 1:39
5
\$\begingroup\$

dc, 14 bytes

0[+?z2=a]dsaxp

Try it online!

Explanation:

 [      ] sa   # recursive macro stored in register a, does the following:
  +            # - sum both numbers on stack
               #   (prints to stderr 1st time since there's only 1)
   ?           # - read next line, push to stack as number
    z          # - push size of stack
     2         # - push 2
      =a       # - if stack size = 2, ? yielded something, so recurse
               # - otherwise end macro (implicit)
0              # push 0 (accumulator)
         d     # duplicate macro before storing it
            x  # Call macro
             p # The sum should be on the stack now, so print it
\$\endgroup\$
4
\$\begingroup\$

CJam, 5 bytes

q~]1b

Try it online!

How it works

q     e# Read all input from STDIN.
 ~    e# Evaluate that input, pushing several integers.
  ]   e# Wrap the entire stack in an array.
   1b e# Convert from base 1 to integer.
      e# :+ (reduce by sum) would work as well, but 1b handles empty arrays.
\$\endgroup\$
2
  • \$\begingroup\$ How does 1b sum numbers? \$\endgroup\$ Jun 17, 2017 at 6:33
  • \$\begingroup\$ CJam doesn't require a canonical representation for digits-to-integer conversion; [<x> <y> <z> <w>]<b>b simply computes b³x + b²y + bz + w. When b = 1, this gives x + y + z + w. \$\endgroup\$
    – Dennis
    Jun 17, 2017 at 6:41
4
\$\begingroup\$

Python, 38 30 bytes

lambda n:sum(map(int,open(n)))

In python, files are opened by open('filename') (obviously). They are, however, iterables. Each time you iterate through the file, you get the next line. So map iterates over each list, calling int on it, and then sums the resulting list.

Call with the filename as input. (i.e. f('numbers.txt'))

8 bytes saved by using map(int, open(n)) instead of a list comprehension. Original code:

lambda n:sum([int(i)for i in open(n)]) 
\$\endgroup\$
4
  • 1
    \$\begingroup\$ I believe that you can also do this with standard input by calling 'open(0)'. Not sure if that can be used to shorten your answer. \$\endgroup\$
    – cole
    Mar 24, 2017 at 0:01
  • \$\begingroup\$ @Cole dennis already has that solution, so I'll leave my answer like this. \$\endgroup\$
    – Riker
    Mar 24, 2017 at 0:06
  • \$\begingroup\$ My mistake, sorry about that; I didn't read all the way through before coming to your answer. \$\endgroup\$
    – cole
    Mar 24, 2017 at 1:31
  • \$\begingroup\$ @Cole it's okay, I don't mind. \$\endgroup\$
    – Riker
    Mar 24, 2017 at 2:29
4
\$\begingroup\$

Mathematica, 19 bytes

Assumes Mathematica's notebook environment.

Tr[#&@@@Import@"a"]

Expects the input to be in a file a.

\$\endgroup\$
3
  • \$\begingroup\$ It's a crazy language :) \$\endgroup\$
    – user9206
    Mar 23, 2017 at 22:20
  • 4
    \$\begingroup\$ @Lembik normal people would write this very readably as Total @ Flatten @ Import @ "a" or even "a" // Import // Flatten // Total. ;) \$\endgroup\$ Mar 23, 2017 at 22:32
  • \$\begingroup\$ Wouldn't Tr[#&@@@Import@#]& also be allowed? \$\endgroup\$
    – ngenisis
    Mar 24, 2017 at 18:27
4
\$\begingroup\$

Jelly, 9 8 bytes

ƈFпFỴVS

STDIN isn't really Jelly's thing...

Try it online!

How it works

ƈFпFỴVS  Main link. No arguments. Implicit argument: 0

  п      While loop; while the condition returns a truthy value, execute the body
          and set the return value to the result. Collect all results (including 0,
          the initial return value) in an array and return that array.
ƈ           Body: Yield a character from STDIN or [] if the input is exhausted.
 F          Condition: Flatten, mapping 0 to [], '0' to "0", and [] to [] (falsy).
    F     Flatten the result.
     Ỵ    Split at newlines.
      V   Evaluate the resulting strings.
       S  Take the sum.
\$\endgroup\$
1
  • 1
    \$\begingroup\$ The second F could be a as well, for clarity. \$\endgroup\$ Mar 24, 2017 at 10:09
4
\$\begingroup\$

Brachylog, 4 bytes

ṇịᵐ+

Try it online!

Explanation

ṇ         Split the Input on linebreaks
 ịᵐ       Map: String to Integer
   +      Sum
\$\endgroup\$
4
\$\begingroup\$

Pure bash, 30

read -d_ b
echo $[${b//'
'/+}]

Try it online.

  • reads the input file in one go into the variable b. -d_ tells read that the line delimiter is _ instead of newline
  • ${b//'newline'/+} replaces the newlines in b with +
  • echo $[ ... ] arithmetically evaluates the resulting expression and outputs it.
\$\endgroup\$
3
  • \$\begingroup\$ +1 Very nice. Is the trailing newline of a input file read as well? I ask because if it is replaced by '+', the $[] section will error due to a trailing '+'. \$\endgroup\$
    – seshoumara
    Mar 25, 2017 at 7:48
  • \$\begingroup\$ @seshoumara It appears that read discards final trailing newlines, even though the line delimiter is overridden to _. This is perhaps a caveat of read, but it works well for this situation. \$\endgroup\$ Mar 25, 2017 at 21:35
  • \$\begingroup\$ I am always happy to see a pure bash solution. \$\endgroup\$
    – user9206
    Mar 26, 2017 at 20:03
3
\$\begingroup\$

Vim, 16 bytes/keystrokes

:%s/\n/+
C<C-r>=<C-r>"<C-h>

Since V is backwards compatible, you can Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Is this either reading from standard in or from a file? \$\endgroup\$
    – user9206
    Mar 23, 2017 at 22:39
  • \$\begingroup\$ Yeah, Vim might not be allowed...:( \$\endgroup\$ Apr 9, 2017 at 21:03
3
\$\begingroup\$

Pyth, 3 bytes

s.Q

Try it online!

 .Q  Read all of standard input, evaluating each line.
s    Take the sum.
\$\endgroup\$
3
\$\begingroup\$

jq, 5 bytes

add, plus the command line flag -s.

For example:

% echo "1\n2\n3\n4\n5" | jq -s add
15
\$\endgroup\$
3
  • \$\begingroup\$ 6 bytes. Since -sadd won't work, count the space. \$\endgroup\$
    – agc
    Mar 25, 2017 at 16:37
  • \$\begingroup\$ @agc Correct me if I'm wrong but the code itself is add (3 bytes) and you have to add 2 bytes for the -s flag. The space doesn't count as the code or the flag: it's the command line separator used by the language. \$\endgroup\$ Mar 28, 2017 at 21:01
  • 1
    \$\begingroup\$ @ThisGuy, Well the -s flag is short for "--slurp", (read the entire input stream into a large array and run the filter just once), which changes both how jq interprets the input data, and how it runs the code. It's not like the -ein sed which merely tells sed that the subsequent string is code. The -s is more like a part of the jq language itself, and therefore that 6th byte space would be too. \$\endgroup\$
    – agc
    Mar 29, 2017 at 4:01
3
\$\begingroup\$

Actually, 2 bytes

Try it online!

Explanation:

kΣ
    (implicit input - read each line, evaluate it, and push it to the stack)
k   pop all stack elements and push them as a list
 Σ  sum
    (implicit output)
\$\endgroup\$
3
\$\begingroup\$

dc, 22

[pq]sq0[?z2>q+lmx]dsmx

This seems rather longer than it should be, but it is tricky to decide when the end of the file is reached. The only way I can think of to do this is check the stack length after the ? command.

Try it online.

[pq]                    # macro to `p`rint top-of-stack, then `q`uit the program
    sq                  # save the above macro in the `q` register
      0                 # push `0` to the stack.  Each input number is added to this (stack accumulator)
       [         ]      # macro to:
        ?               # - read line of input
         z              # - push stack length to stack
          2             # - push 2 to the stack
           >q           # - if 2 > stack length then invoke macro stored in `q` register
             +          # - add input to stack accumulator
              lmx       # - load macro stored in `m` register and execute it
                  d     # duplicate macro
                   sm   # store in register `m`
                     x  # execute macro

Note the macro m is called recursively. Modern dc implements tail recursion for this sort of thing, so there should be no worries about overflowing the stack.

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to PPCG! Please note that if there isn't enough explanations it will go through the low quality posts filter. \$\endgroup\$ Mar 25, 2017 at 2:40
  • \$\begingroup\$ @SIGSEGV no welcome necessary - I've been here a while ;-). Yep, I was writing my explanation while you commented. See edit. \$\endgroup\$ Mar 25, 2017 at 3:22
  • 1
    \$\begingroup\$ I owe you a byte for the trick of duplicating the macro before storing it. \$\endgroup\$ Mar 27, 2017 at 20:01
2
\$\begingroup\$

Pyke, 4 bytes

zbrs

Try it online!

z    -   input()
 b   -  int(^)
  r  - if no errors: goto start
   s - sum(stack)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy