รวมตัวเลขตามมาตรฐานใน


32

พิจารณาสตรีม / ไฟล์ที่มีจำนวนเต็มหนึ่งตัวต่อบรรทัด ตัวอย่างเช่น:

123
5
99

227รหัสของคุณควรส่งออกผลรวมของตัวเลขเหล่านี้ว่าเป็น

รูปแบบการป้อนข้อมูลเป็นจำนวนเต็มหนึ่งจำนวนต่อหนึ่งบรรทัดอย่างเคร่งครัด ตัวอย่างเช่นคุณไม่สามารถสมมติว่าอินพุตอยู่ในหนึ่งบรรทัดเป็นอาร์เรย์ของจำนวนเต็ม

คุณสามารถรับอินพุตจาก STDIN ในรูปแบบของชื่อไฟล์หรือไฟล์ที่มีชื่อที่คุณเลือก คุณสามารถเลือกได้ ไม่อนุญาตให้ใช้วิธีอื่นในการป้อนข้อมูล

อินพุตจะมีจำนวนเต็มอย่างน้อยหนึ่งตัว คุณสามารถสันนิษฐานได้ว่าจำนวนเต็มทั้งหมดจะไม่ใช่เชิงลบและผลรวมของพวกเขาคือน้อยกว่า232


2
มีการขึ้นบรรทัดใหม่หรือไม่? ขึ้นบรรทัดใหม่ว่าเป็นตัวเลือกหรือไม่
โปรดหยุดความชั่วร้ายเมื่อ

9
Hi! ฉันลงคะแนนความท้าทายนี้เพราะมันขัดกับมาตรฐานชุมชนของเราสำหรับรูปแบบอินพุต / เอาต์พุตที่ยอมรับได้โดยมีรูปแบบอินพุตที่ จำกัด
AdmBorkBork

1
@AdmBorkBork และฉันพูดถึงเรื่องนี้ในห้องแชท เราได้ตกลงที่จะไม่เห็นด้วย :)

22
ในฐานะผู้เขียนสิ่งที่ต้องหลีกเลี่ยงจากI / O ที่ยุ่งยากและการเอาชนะค่าเริ่มต้นโดยพลการฉันต้องการที่จะปกป้องความท้าทายนี้ในพื้นที่เหล่านั้น ที่นี่อินพุตการประมวลผลเป็นเนื้อของความท้าทายไม่ใช่งานพิเศษที่เบี่ยงเบนความสนใจจากความท้าทายหลัก ไม่ใช่ "เพิ่มตัวเลข" ที่มีข้อกำหนด I / O แปลก ๆ แต่เป็น "ดำเนินการ I / O นี้" ด้วยการเพิ่มเป็นขั้นตอน การยกเลิก I / O มาตรฐานเป็นสิ่งจำเป็นสำหรับคำตอบที่จะไม่ให้ทางลัดข้ามงานหลัก
xnor

2
ทำไมฟังก์ชั่นอินพุทที่ไม่สามารถใช้ได้?
CalculatorFeline

คำตอบ:



21

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.

I like this. It's nice and clever.

Could you use tr \\n + Instead without xargs?

1
@Lembik Do you mean tr \\n +|bc? If so, then please see the updated explanation. Good question.
seshoumara

paste -s -d+|bc is 15 bytes
David Conrad

1
@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.
seshoumara

14

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.



12

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!


1
Very neat and tidy.

Ooh, I had paste -s -d+|bc and didn't realize I could consolidate the switches. Neat!
David Conrad

12

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.

What is it perl 5?

14
this reads like lolcode
Bryan Boettcher

@Lembik it is clearly labeled as Perl 6, which is a sister language to Perl 5.
Brad Gilbert b2gills

There was a typo. I meant what is it in Perl 5?

1
Well $a+=$_ for <>;print $a works in Perl 5, but there may be a shorter way.
Brad Gilbert b2gills



9

Retina, 11 7 bytes

-4 thanks to Martin Ender

.*
$*
1

Try it online!


Convert to unary:

.*
$*

Count the number of 1s:

1

1
Interesting how Retina, as a regex based language, can do the sum in fewer bytes than the shortest bash answer posted so far. +1
seshoumara

Is this reading from standard in?

2
@Lembik Yes it is.
Riley

If input in unary was allowed, it'd be only one byte.
mbomb007

@mbomb007 I already tried that in sed.
Riley

8

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.

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

1
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.
Riley



7

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.


I can't even parse it! :) Explanation please.

@Lembik Here you go.
Dada

The unmatched parenthesise part is very obscure!

@Lembik Those aren't parenthesizes... They're either French or Curly Braces depends on who you ask, but they definitely are not )(
CraigR8806

1
@Lembik accolades, apparently.
Michael Vehrs

7

Pure Bash, 37 36 bytes

Thanks to @KevinCruijssen for a byte!

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

Try it online!


3
Very nice and clean.

I never program in Bash, but isn't it possible to remove the space between do ((? The TIO seems to work.
Kevin Cruijssen

@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.
betseg

6

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

1
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.
Stefan Aleksić

6

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.


5

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

1
"Explanation coming soon™" That'd be my new catchphrase if it weren't trademarked...
ETHproductions

2
In the language of awk, your answer is actually only 19 bytes: {s+=$1}END{print s} :)
Digital Trauma

5

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

4

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.

How does 1b sum numbers?
Esolanging Fruit

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

4

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

1
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.
cole

@Cole dennis already has that solution, so I'll leave my answer like this.
Rɪᴋᴇʀ

My mistake, sorry about that; I didn't read all the way through before coming to your answer.
cole

@Cole it's okay, I don't mind.
Rɪᴋᴇʀ

4

Mathematica, 19 bytes

Assumes Mathematica's notebook environment.

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

Expects the input to be in a file a.


It's a crazy language :)

4
@Lembik normal people would write this very readably as Total @ Flatten @ Import @ "a" or even "a" // Import // Flatten // Total. ;)
Martin Ender

Wouldn't Tr[#&@@@Import@#]& also be allowed?
ngenisis

4

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.

1
The second F could be a as well, for clarity.
Erik the Outgolfer


4

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.

+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 '+'.
seshoumara

@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.
Digital Trauma

I am always happy to see a pure bash solution.



3

jq, 5 bytes

add, plus the command line flag -s.

For example:

% echo "1\n2\n3\n4\n5" | jq -s add
15

6 bytes. Since -sadd won't work, count the space.
agc

@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.
caird coinheringaahing

1
@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.
agc


3

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.


Welcome to PPCG! Please note that if there isn't enough explanations it will go through the low quality posts filter.
Matthew Roh

@SIGSEGV no welcome necessary - I've been here a while ;-). Yep, I was writing my explanation while you commented. See edit.
Digital Trauma

1
I owe you a byte for the trick of duplicating the macro before storing it.
Brian McCutchon

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.