32
\$\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\$
  • 2
    \$\begingroup\$ Is there a trailing newline? Is that newline optional? \$\endgroup\$ – the dark wanderer Mar 24 '17 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\$ – AdmBorkBork Mar 24 '17 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 '17 at 17:09
  • 22
    \$\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 '17 at 18:58
  • 2
    \$\begingroup\$ Why can't function input be used? \$\endgroup\$ – CalculatorFeline Apr 9 '17 at 21:02

74 Answers 74

1
\$\begingroup\$

Lua, 59 bytes 57 bytes

New code: 57 bytes

i,s=0,0;repeat i,s=i+s,io.read("*l")until not s print(i)

We initialize i and s to 0. For each iteration, we add s to i and load in a new s from stdin. Lua has implicit string -> number coercions when doing numeric operations on a string.


Old code: 59 bytes

i=0;io.read("*a"):gsub(".-\n",function(g)i=i+g end)print(i)

Takes entire stdin and turns it into a string, gsubs over the entire string to extract lines, uses implicit number conversion and adds the lines to i, then prints i.

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

Carrot, 6 bytes

#^A
+ 

Note the trailing space after the +.

Explanation:

#   //Set the stack to the entire input
^   //Convert to operations mode
A\n //Split the stack into an array on a new line
+   //Add all the arguments of the array together
    //Implicitly output the result
\$\endgroup\$
  • \$\begingroup\$ This is one of the reasons I am doing the rewrite of Carrot. With the new lexer, the space after + would not be needed as it will be understood that + takes no arguments. \$\endgroup\$ – Cows quack Jul 19 '17 at 13:16
  • \$\begingroup\$ @Cowsquack Ah nice that'll be good. \$\endgroup\$ – TheLethalCoder Jul 19 '17 at 13:17
1
\$\begingroup\$

Ly, 2 bytes

&+

Try it online!

A Ly builtin that would beat the accepted answer if it wasn't a 2-byte builtin...

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

Triangular, 15 bytes

(\$]U]P.%p/+U(<

Try it online!

Formats into this triangle:

    (
   \ $
  ] U ]
 P . % p
/ + U ( <

Explanation:

The IP starts from the top of the triangle, moving Southeast. So the first code that is executed is this:

($]

That simply reads integers as input until there is no more input.

This is how the interpreter sees the next part:

p(U+P]U%
  • p pops the EOF from the stack.
  • ( opens a loop (to add the inputted integers).
  • U pulls the "memory" (register) value onto the stack if it is not zero.
  • + adds the top two stack values together, pops them, and pushes the result.
  • P pops the top of stack into memory. Now, if we've added all inputted integers together, nothing will be on the stack.
  • ] ends the loop if the top of the stack is falsy (or the stack is empty).
  • U pulls the memory value onto the stack.
  • % prints it.
  • Another loop is created at the end of the code, but that doesn't do anything as the IP runs off the playing field and terminates.
\$\endgroup\$
1
\$\begingroup\$

q/kdb+, 14 bytes

Solution:

sum"J"$(0:)`:f

Example:

q)system "cat f" / check contents of file f
"123"
,"5"
"99"
q)sum"J"$(0:)`:f
227

Explanation:

Read in the file called f, cast to longs, sum up:

sum"J"$read0`:f / ungolfed solution
            `:f / our input file f
       read0    / read in a file, break on newlines
   "J"$         / parse strings to longs
sum             / sum it up

Bonus:

The solution in K4 is 10 bytes. Eequivalent to sum value each read0 `:f in Q:

+/.:'0:`:f
\$\endgroup\$
1
\$\begingroup\$

Wumpus, 11 8 bytes

I+0i.
O@

Try it online!

Explanation

As long as there are numbers left to read, the program loops through the first line:

I   Read a decimal integer from STDIN.
+   Add it to the top of the stack. Initially, the stack is empty, which adds
    the first number to an implicit zero.
0   Push 0.
i   Read the next byte. If there are numbers left, this will be a 10 (for the
    separating linefeed). Otherwise, we're at EOF and this gives -1.
.   Jump to (0, x), where x is the byte we just read, modulo 2 (because the
    program is 2 rows tall). So for a linefeed, this jumps to the beginning
    of the first line, and at EOF this jumps to the beginning of the second
    line.

Once we run out of numbers to add, control flow goes to the second line:

O   Print the sum as a decimal integer.
@   Terminate the program.
\$\endgroup\$
1
\$\begingroup\$

Flobnar, 16 12 bytes

-4 bytes thanks to @JoKing

+>p*
^@
>&06

Try it online! Requires the -d flag.

As a bonus, this works if no numbers are passed, and supports pretty much any separator other than digits and -.

\$\endgroup\$
  • \$\begingroup\$ 12 bytes \$\endgroup\$ – Jo King Aug 17 '18 at 11:05
  • \$\begingroup\$ @JoKing I have no idea how that works, but ok... \$\endgroup\$ – Esolanging Fruit Aug 19 '18 at 7:03
1
\$\begingroup\$

APL (Dyalog Unicode), 12 bytes

Complete program.

+/⍎⍕⊃⎕NGET⍞1

Try it online!

 read filename from stdin

⊃⎕NGET1 get native file content as list of strings

 stringify (puts two spaces between lines)

 execute (as APL code)

+/ sum

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

Sinclair ZX81 (16K only - probably*) File size according to EightyOne - 163** bytes (yes 163!) Byte count undetermined

Firstly, we should make our file, so using direct mode, type:

LET A=123
LET B=5
LET C=99

To make sure that they are there, print them to the screen, as follows:

PRINT A,,B,,C

This should appear on the display:

ZX81 variable output

Now, to save this to file (as the variable stack is saved along with other important memory locations used by the interpreter), simply type:

SAVE "SUM"

If you're using a real ZX81 then press play and record on tape, whilst emulators like EightyOne will create a tape image for you.

Now clear the RAMs with:

RAND USR 0

or:

NEW

Now rewind the tape (or the emulator should auto-detect and start the virtual tape from the beginning), and type:

LOAD "SUM"

So our file is back in memories, so we need to add it together. Simply:

PRINT A+B+C

And the answer is:

The ZX81 final output

*I specify 16K because any less and the ZX81 will typically rearrange the memory and this could affect the var stack (mostly to do with collapsing the DFILE), as the DFILE is static with 16K then this should be less of an issue.

**The ZX81 file is saving more than just the VAR stack of three whole variables above, and although each number appears to be an integer, the ZX81 is storing these variables as 24-bit floating point numbers rather than 1 byte integers.

\$\endgroup\$
  • \$\begingroup\$ Utterly brilliant . Let's not mention the spec :) \$\endgroup\$ – user9206 Mar 24 '17 at 10:03
  • \$\begingroup\$ I'm confused what the actual code is. Is that PRINT A+B+C part of it? Would it be invalid then if there are more or less than 3 numbers? \$\endgroup\$ – Luis Mendo Mar 24 '17 at 11:45
  • \$\begingroup\$ The challenge seemed to specifically require a file, and to do that on a ZX81 you need to save your values somewhere. I decided to use the 24-bit floating point variables that I named A, B, and C. I could have POKEd these values to a spare bit of memory but I'm not sure if it'll save. So if you wanted more variables, then you'd need to initialise and declare more variables, so if LET D=321 and that was SAVEd then to add up the file contents, one would PRINT A+B+C+D. I could save to a string but I'd been some way to separate each individual number by a comma, for instance. \$\endgroup\$ – Shaun Bebbers Mar 24 '17 at 11:53
  • \$\begingroup\$ Remember, I initialised and declared the variable values, then saved that to a file before clearing the memory. I then loaded back the file using the ZX81's equivalent of standard in - once the file was loaded, the variables were back in memory, so therefore I could use the PRINT keyword to add up and output the values. \$\endgroup\$ – Shaun Bebbers Mar 24 '17 at 11:56
  • 1
    \$\begingroup\$ @ShaunBebbers The same program needs to work for an arbitrary number of values without modification. \$\endgroup\$ – AJMansfield Mar 25 '17 at 7:01
0
\$\begingroup\$

Anyfix, 4 bytes

ɦ€#S

Explanation

ɦ€#S  Program
ɦ     Exhaust input; read into a list of lines
 €    Map: 
  #        Parse to number
   S  Sum
\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 27 bytes

s=>eval(s.split`
`.join`+`)

Try it

f=
s=>eval(s.split`
`.join`+`)
oninput=_=>o.innerText=f(i.value);o.innerText=f(i.value=`123\n5\n99`)
textarea{font-family:sans-serif;height:100px;width:100px;}
<textarea id=i></textarea><pre id=o>


Explanation

  • Takes input as a multiline string via parameter s.
  • Splits the string to an array on newlines.
  • Joins the array to a string on +.
  • Evals the string to give us the sum.

Alternative, 23 bytes

If we could take each integer as an individual argument of our function then we could do this:

(...a)=>eval(a.join`+`)

Alternative, 63 bytes

If we have to take a file name as input then use this version instead:

p=>fetch(p).then(r=>r.text()).then(s=>eval(s.split`
`.join`+`))
\$\endgroup\$
0
\$\begingroup\$

Stax, 2 bytes

|+

Run and debug it

Also prints intermediate results, which doesn't appear to be disallowed

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

C++, 98 bytes

#include<regex>
namespace std{int::main(){istream_iterator<int>a{cin},b;cout<<accumulate(a,b,0);}}

Ungolfed

#include <iterator>
#include <numeric>
#include <iostream>

int main()
{
    std::istream_iterator<int> first{std::cin};
    std::istream_iterator<int> last{};
    std::cout << std::accumulate(first, last, 0);
}

We have std::istream_iterator to read input as whitespace-separated integers, and std::accumulate to add them up.

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

Ahead, 13 bytes

~Ilj~#
 >K+O@

Try it online!

\$\endgroup\$

Your Answer

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