Sum of positive integers.

14

0

Problem:

Given a set of integers, find the sum of all positive integers in it.

Input:

  • t – number of test cases [t < 1000]
  • On each of next t lines, an integer N [-1000 ≤ N ≤ 1000]

Output

The program should output the sum of all the positive integers.

Check your code in online judge

Score

Score is equal to size of source code of your program except symbols with ASCII code ≤ 32.

Here is the best score list: Python Best Scores (Best score is 29)

gmunkhbaatarmn

Posted 2011-02-24T09:59:28.223

Reputation: 457

Question was closed 2016-04-23T22:47:54.157

Shouldn't the example on SPOJ provide an output of 15? 4+5+6? Or am I missing something? – MrZander – 2012-03-22T22:51:18.770

Where's the specification? Nowhere to be found: SE questions should be self-contained. – cat – 2016-04-23T18:10:04.550

How is this question unclear? [1, 2, 3, 4] --> 10. I'm voting to close this question not because it's unclear, but because it's a challenge from another site, which is off-topic according to community consensus

– James – 2016-04-23T20:13:36.597

13

There are a lot more codegolf challenges at http://www.spoj.pl/SHORTEN/. Don't see the point of duplicating them here though.

– hallvabo – 2011-02-24T12:22:47.780

3why is this question tagged python.. Are we interested in python solution only? – Aman ZeeK Verma – 2011-02-24T13:56:01.577

24I don't think questions from contest sites should be posted here. – fR0DDY – 2011-02-24T14:01:36.280

2I already did this one on SPOJ. A while ago they promoted all the Python2.6 answers to Python3 even though some of them wont run under Python3 and would be longer in Python3 - eg have to use int(input()) instead of input() and print(x) instead of print x. So I don't take SPOJ very seriously anymore. I'm tied with Tim Peters and that's good enough for me :) – gnibbler – 2011-02-24T21:22:04.217

@fR0DDY, Yes, in this case if someone posted the 29 char Python solution, everyone who sees this question can get a good rank on SPOJ without earning it – gnibbler – 2011-02-25T01:25:25.793

4I just want to point out, that skipping the T (number of ...errr...numbers (?) ) is not an option...since the testcases involve extra data after T numbers...your code will fail at SPOJ. Everyone (3 answers below) seemed to have cleverly skipped the first integer. – st0le – 2011-02-25T09:36:14.013

Please, check my Python( 41 char) solution, if it correct or not. I had some doubt regarding the use of \n in my source code. – Coding man – 2014-03-05T15:51:25.643

1Since answers are moving up and down, '3 answers below' is not very precise. – user unknown – 2011-10-13T14:29:35.700

Answers

34

Whitespace, 0

I couldn't resist. S= space, T= tab, N = newline, all have ASCII codes <= 32.

SSSSNSSSSNTTSSSSSTNTNTTNSSSNSSSSTNTTTNTSTNSSSSTNSSSSTNTTTSSSSTNTSSTTTSSSSSTSNTNTTSSSSTSNTTTNTTSNSSSSNSSSSTSNTTTSSSSNTTTTSSSTTSNSNSNNSSTNSSSSNTTTTNSTSSSSTSTSNTNSSNNN

Base64 encoded for easy copy & paste.

ICAgIAogICAgCgkJICAgICAJCgkKCQkKICAgCiAgICAJCgkJCQoJIAkKICAgIAkKICAgIAkKCQkJ
ICAgIAkKCSAgCQkJICAgICAJIAoJCgkJICAgIAkgCgkJCQoJCSAKICAgIAogICAgCSAKCQkJICAg
IAoJCQkJICAgCQkgCiAKIAoKICAJCiAgICAKCQkJCQogCSAgICAJIAkgCgkKICAKCgo=

hammar

Posted 2011-02-24T09:59:28.223

Reputation: 4 011

3(+1) Nice program! A tiny "FWIW": 9 characters can be removed due to 9 instances of an unneeded S in the binary coding of a number. These are all in push-number-to-stack instructions of the form SSSS...N, where the 4th S codes a superfluous leading 0. (Of course this has no effect on the score.) – r.e.s. – 2012-03-29T12:18:29.397

13

Element, 17 characters plus 1 space

_'[_ 2:n;0>[n~+]]`

This is my first constructed language. It is designed to be very compact and human-readable. All of the instructions are one character long and perform a single function.

Element has two stacks and a hash as memory structures. The two stacks are called the main stack and the control stack. The main stack is where arithmetic, I/O, and hash manipulation occurs. The control stack is where logic operations occur, and this stack controls the while and for loops.

The basic idea behind Element is that there is a hash that stores numbers/strings, while the stack is used to perform calculations on these numbers. The results to these calculation can then assigned a certain place in the hash for future use. The different contents of the hash are called elements, so it is similar to an array but can have non-numerical names.

EDIT: You can find an interpreter for Element (written in Perl) here.

Here is the list of operators: In some of these examples, m and n represent numbers already on the stack.

text  --pushes the string "text" onto the main stack
'     --pops from main stack and pushes onto control stack
"     --pops from control stack and pushes onto main stack
#     --pops from main stack and destroys
[]    --FOR statement (view the top number number from control stack and eval those many times)
{}    --WHILE (loop until top number on control stack is 0)
(     --pops from main stack, removes first character, pushes the remaining string onto stack, and pushes the removed character onto stack
)     --pops from main stack, removes last character, pushes the remaining string onto stack, and pushes the removed character onto stack
~     --pops from main stack, pushes contents of the element with that name
+-*/%^ --pops two most recently named elements, adds/negates/multiplies/divides/modulates/exponentiates them, and places the result on the stack
mn;   --pops m and n and assigns element n the value of m
mn@   --pops m and n and moves mth thing in stack to move to place n in stack
m$    --pops m and pushs size of m onto the stack
mn:   --pops m and n and pushes m onto the stack n times
mn.   --pops m and n and pushes m concatonated with n
m?    --pops m and pushes 0 onto control stack if m is '0' or and empty string, else pushes 1 
\     --escapes out of next character, so it isn't an operator and con be pushed onto the stack
><=   --pops two numbers off of stack and tests, pushes 1 onto control stack if true and 0 if false
`     --pops from main stack and prints
&|    --pops two items from control stack, performs and/or respectively, and pushes result back onto control stack
!     --pops a number off of control stack, pushes 1 if 0 or empty string, 0 otherwise
_     --inputs a word and pushes onto main stack
m,    --pops m from main stack, coverts it to char and pushes, converts to num and pushes
Newlines and spaces separate different elements to be pushed onto the stack individually, but can pushed onto the stack using \

Here is a walkthrough of how the program works:

_'[    --take the first line of input, transfer it to the control stack, and start a for loop
_ 2:   --take one more line of input, and duplicate it so that there are two copies
n;     --take one copy and put into element n
0>     --push a zero onto the stack, remove the zero and the other copy of the input, and compare. A 1 will be placed on the control stack if the input was greater than zero, a 0 otherwise.
[      --starts another for loop if the comparison was true. This loop will be repeated once if the comparison was true and no times if it was false, so it is the same as an IF statement.
n~     --pushes n onto the main stack, then pops it ans replaces it with the contents of n, which is the number stored earlier
+      --takes the number and adds it to the running total, which is contained as the last item on the stack
]      --ends the inner for loop
]      --ends the outer for loop
`      --print the top item (also the only item) on the stack to output

PhiNotPi

Posted 2011-02-24T09:59:28.223

Reputation: 26 739

3@WChargin he is used to Perl... – Caridorc – 2015-02-10T15:20:20.873

@WChargin Every language is unreadable until you learn it. ;) – Martin Ender – 2015-02-10T23:53:24.653

6An entry like this would be much improved with a pointer to a working environment. – dmckee --- ex-moderator kitten – 2012-03-26T04:09:09.987

5I don't think you understand what "human-readable" means. – wchargin – 2014-02-25T02:44:13.860

8

Perl, 31

<>;$i+=$_*($_>0)while<>;print$i

Timwi

Posted 2011-02-24T09:59:28.223

Reputation: 12 158

Wouldn't using say make this just a bit shorter? It'd tie with the 29 character best. – Mr. Llama – 2012-04-23T15:52:59.897

No, because say isn’t built-in and (at least) requires a command-line switch which would count towards the character count. – Timwi – 2012-04-23T18:19:22.327

It can be shortened to 29 bytes by using $\ instead of $i: <>;$\+=$_*($_>0)while<>;print – Heiko Oberdiek – 2014-03-05T09:59:32.413

5

Ruby 1.9.2, 37

p eval [*$<].join.gsub(/\A\d+|-\d+|\n/, '+0')

Call like ruby scriptname file_with_ints .

steenslag

Posted 2011-02-24T09:59:28.223

Reputation: 2 070

I can't read much Ruby, but does that even read the number of test cases? – Joey – 2011-02-25T09:15:50.553

No it doesn't... – st0le – 2011-02-25T09:31:37.517

@st0le: Just noticed that apparently no solution currently solves the task. – Joey – 2011-02-25T23:49:16.497

5

Ruby, 52

t=gets.to_i;s=0;t.times{i=gets.to_i;s+=i if i>0};p s

david4dev

Posted 2011-02-24T09:59:28.223

Reputation: 665

I don't see where you are printing the value of s. – Wile E. Coyote – 2011-02-27T18:27:09.287

yeah I forgot

– david4dev – 2011-02-27T19:21:40.477

5

Haskell, 58

Properly operates on only t integers. Haven't run it against Spoj because I just don't care to register there.

f (x:l) = take x l
main = interact $ show . sum . f . map (max 0.read) . lines

user1011

Posted 2011-02-24T09:59:28.223

Reputation:

What are "t integers"? – wchargin – 2015-02-10T20:25:16.450

4

Perl, 33

<>;while(<>){$i+=$_ if$_>0}print$i

Although the space is necessary, so it seems odd not to count it. Oh well, the rules is the rules.

Hmm. I could probably get away with using a variable name which doesn't count towards the total either. The thing is, I'm not sure how I'd paste the code then.

Peter Taylor

Posted 2011-02-24T09:59:28.223

Reputation: 41 901

Just show them as $^A-$^Z, but beware that many of that variables have special meanings. – ninjalj – 2011-02-24T20:58:34.483

4

code in C 89 characters


x="%d";  main(b,a,t)  {  
  for(scanf(x,&t);t;t--)
    {  scanf(x,&a); a>0?b+=a:a; }  printf(x,b-1);
       return 0; }

I tried a lot to reduce my code less than 63 bytes, but i can reduce it only to 89 bytes. Please help me to reduce it to 63 bytes or even less.

avinashse

Posted 2011-02-24T09:59:28.223

Reputation: 177

>

  • I have counted 90 characters.
  • return 0; is not necessary, the for cycle may be contracted to for(scanf(x,&t);t--;scanf(x,&a),a>0?b+=a:a); == which make that 78 characters...
  • < – V-X – 2014-03-05T11:34:20.277

    Doesn't compiles with gcc 4.8.1 error: initializer element is not computable at load time x="%d" – manav m-n – 2014-07-21T08:49:00.623

    3

    Clojure, 71

    (reduce + (filter pos? (map #(Integer/parseInt %) (next (line-seq *in*)))))
    

    Meikel

    Posted 2011-02-24T09:59:28.223

    Reputation: 51

    This doesn't produce any output, and fails because *in* is not a java.io.BufferedReader, as required by line-seq. – John Cromartie – 2013-07-11T15:24:48.383

    Also it ignores the number of lines input t. – John Cromartie – 2013-07-11T15:39:35.420

    3

    In memoriam Dennis M. Ritchie

    unix 57¹72:

    n=$(head -n1 i); echo $(($(head -n $((n+1)) i | tail -n $n | grep -v "-" | tr '\n' '+')0))
    

    assuming i is the file, containing the ints.

    ¹) was wrong, included the number of lines, and added 1 line too less.

    echo $(($(cat i | head -n $(head -n1 i) | grep -v "-" | tr '\n' '+')0))

    user unknown

    Posted 2011-02-24T09:59:28.223

    Reputation: 4 210

    2

    Haskell, 51

    main = interact $ show . f . lines
    f (x:l) = foldl (+) 0 $ map read l
    

    (extra spaces for clarity, since they don't count)

    Haskell is ... interesting, since you tend to get programs with a significant number of necessary spaces.

    Anon.

    Posted 2011-02-24T09:59:28.223

    Reputation: 1 799

    2You forgot a filter (>0). – FUZxxl – 2011-04-10T14:58:30.463

    2

    Mathematica: 18 16

    Boole[#>0]&/@x.x
    

    Corey Kelly

    Posted 2011-02-24T09:59:28.223

    Reputation: 121

    Nice function, but how does this handle the specified newline-separated input? How does it not incorporate the number of test cases parameter t as part of the sum? How does it sum only up to the number of test cases specified, even if more are given? – Jonathan Van Matre – 2014-03-05T23:08:44.520

    2

    C,88


    x="%d";  main(b,a,t)  {  
    for(scanf(x,&t);t--;)  
    {  scanf(x,&a); a>0?b+=a:0; }  printf(x,b-1);
    return 0; }
    

    After another big effort, code is one character less, please help me to reduce it more.

    avinashse

    Posted 2011-02-24T09:59:28.223

    Reputation: 177

    remove the (return 0;) and ({} for for) – l0n3sh4rk – 2012-04-21T19:39:43.283

    b,x="%d";main(a,t){for(scanf(x,&t);t--&&scanf(x,&a);)b+=(a>0)*a;printf(x,b);} <- 77 bytes – walpen – 2012-06-09T19:59:40.510

    @walpen: they used the fact, that their "argc" like parameter was set to 1, your b is uninitialized... – V-X – 2014-03-05T12:18:10.070

    6just edit the original answer next time – ratchet freak – 2011-07-03T19:18:24.757

    2

    Befunge-98 (24)

    (Make sure you use an interpreter that can read negative numbers (seems to be a somewhat common bug, but RcFunge works))

    <;-1\+*`0:&\_\#;.@;:;#&0 
    

    Perl (25)

    (Perl allows control characters in variable names, I named my variable ^B (ASCII 2) so that it does not count towards the goal.)

    <>;$^B+=$_*!/-/for<>;print$^B

    (Normal variant (27 chars)):

    <>;$B+=$_*!/-/for<>;print$B
    

    marinus

    Posted 2011-02-24T09:59:28.223

    Reputation: 30 224

    i first ignored your perl answer when i saw the variable naming and completely missed the excellent one below it – ardnew – 2013-07-09T22:55:32.590

    2

    APL (10)

    +/{0⌈⎕}¨⍳⎕
    

    Explanation:

    • ⍳⎕: read a line, gives a list [1..N] for user's input N
    • ¨: for each element in this list... (i.e. do N times)
    • 0⌈⎕: read a line, return the maximum of 0 and the entered N
    • We now have a list with all positive Ns the user entered, and 0s where the user entered something negative.
    • +/ gives the sum of this list.
    • The result is output by default (because we're not doing anything else with it).

    marinus

    Posted 2011-02-24T09:59:28.223

    Reputation: 30 224

    1

    Clojure, 108

    (let [[n & m] (->> *in* java.io.BufferedReader. line-seq (map read-string))]
      (->> m (take n) (filter pos?) (apply +) println))
    

    I really wish I could avoid the java.io.BufferedReader. part, since it costs 24 chars itself. But AFAIK there's no facility to read lines from STDIN without it.

    John Cromartie

    Posted 2011-02-24T09:59:28.223

    Reputation: 111

    1

    PowerShell, 44

    ($i=$input|%{+$_})[1..$i[0]]-gt0-join'+'|iex
    

    Joey

    Posted 2011-02-24T09:59:28.223

    Reputation: 12 260

    1

    Perl, 20

    I know it is old and trivial, but the Perl answer can be still improved:

    #!perl -p
    $.<2or$\+=$_*!/-/}{
    

    nutki

    Posted 2011-02-24T09:59:28.223

    Reputation: 3 634

    This is awesome! But what does }{ mean/do? – daniero – 2015-07-19T13:40:19.393

    1

    Q,12

    {0+/x(&)x>0}
    

    sample usage

    q){0+/x(&)x>0} 1 -1 2 3 -1
    6
    

    tmartin

    Posted 2011-02-24T09:59:28.223

    Reputation: 3 917

    1

    C, 70 72 characters

    s;main(i,c){for(;c--;i>0?s+=i:0)scanf("%d",s?&i:&c);printf("%d",s-1);}
    

    The results on the SPOJ site definitely seem unreal - I have no idea how to get this down to 63.

    However, 68 characters is reachable on some compilers by abusing undefined behaviour. The following works on x86 Linux with 32-bit gcc, on which all arguments are passed on the stack.

    s;main(i,c){for(;c--;i>0?s+=i:0)scanf("%d",&i+!s);printf("%d",s-1);}
    

    han

    Posted 2011-02-24T09:59:28.223

    Reputation: 1 226

    1

    befunge, 3524

    :0`j&1-\&:0`*+\:0`3*j$.@
    

    with a little inspiration by seeing marinus answer, I've also managed 24 characters. but I've got a completely different approach.

    Ali1S232

    Posted 2011-02-24T09:59:28.223

    Reputation: 417

    1

    PYTHON 2.x, 50 chars

    r=input
    print sum(i for i in (r() for j in range(r())) if i>0)
    

    Joel Cornett

    Posted 2011-02-24T09:59:28.223

    Reputation: 361

    1

    excel, 27

    =SUM(INDIRECT("A2:A"&1+A1))
    

    count t in A1, rest of data a2 and down

    SeanC

    Posted 2011-02-24T09:59:28.223

    Reputation: 1 117

    0

    45 chars in python

    c=0
    j=input
    for i in j()*[0]:
        b=j()
        c+=b*(b>0)
    print c
    

    user2274615

    Posted 2011-02-24T09:59:28.223

    Reputation: 1

    1How you counted that? It gives me 54 characters. – manatwork – 2013-07-02T07:02:41.250

    @manatwork, this question has non-standard scoring rules which don't count whitespace. – Peter Taylor – 2013-07-02T11:00:12.400

    Oops, sorry. I missed that. Thanks, @PeterTaylor. – manatwork – 2013-07-02T11:39:24.457

    0

    Python 3, score: 63 61

    r=0
    q=input
    w=int
    for i in[1]*w(q()):
     t=w(q())
     r+=t+abs(t)
    print(r/2)
    

    I don't really know python, so I'm having a considerably difficult time making this any smaller.

    Python, score: 49 48

    r=0
    q=input
    for i in[1]*q():
     t=q()
     r+=t+abs(t)
    print r/2
    

    Same as above, but python 2 doesn't need the casting to int, apparently.

    Cereal

    Posted 2011-02-24T09:59:28.223

    Reputation: 299

    So do I.

    I'm not entirely sure where 49 came from. – Cereal – 2013-07-09T19:34:36.307

    my mistake -- apparently characters with ascii value < 33 are discounted. – boothby – 2013-07-09T19:49:34.103

    if whitespace etc doesn't count, then it's shorter to put "compound" statements like r,q,w=0,input,int as single statements on separate lines; r=0 q=input w=int (where space is newline) – daniero – 2013-07-10T11:40:26.090

    The reason for casting to int in Python 3 is input is not the same function : see this SO answer

    – ThinkChaos – 2014-02-02T11:04:15.310

    0

    Perl, 30

    so close to that python best of 29, but had to add +1 for the -p switch

    $s.=$_}{$s=~s/\s\d+/$_+=$&/eg
    

    ardnew

    Posted 2011-02-24T09:59:28.223

    Reputation: 2 177

    This can be modified into an alternative 20 char solution: -p0 s/\n\d+/$\+=$&/ge}{. 19 when not counting \n. – nutki – 2015-02-11T10:21:01.620

    0

    Python

    One-statement Solution

    Python 3 (60 chars, 66 with spaces)

    print(sum(x for x in(int(input())for _ in[1]*int(input()))if x>0))
    

    Python 2 (48 chars, 55 with spaces)

    print sum(x for x in(input()for _ in[1]*input())if x>0)
    

    May be shortened by one character

    i=input
    print sum(x for x in(i()for _ in[1]*i())if x>0)
    

    AMK

    Posted 2011-02-24T09:59:28.223

    Reputation: 506

    0

    dc, 22 chars

    0?[sa?+la1-d0<b]dsbxrp
    

    Negative numbers must be specified in the dc notation, i.e. with underscore: _20.

    Tomas

    Posted 2011-02-24T09:59:28.223

    Reputation: 2 333

    0

    PERL, 21 chars (score 20)

    $a+=<>for 1..<>;say$a
    

    Tomas

    Posted 2011-02-24T09:59:28.223

    Reputation: 2 333

    I don't get it, how this eliminates negative numbers from the sum? – nutki – 2015-02-11T10:04:03.707

    0

    Smalltalk, 79

    b:=[:x|Number readFrom:Stdin].(((1 to:(b value:1))collect:b)select:[:i|i>0])sum
    

    blabla999

    Posted 2011-02-24T09:59:28.223

    Reputation: 1 869

    0

    Python, 41

    i=input
    print sum(len(" "*i())for j in[0]*i())
    

    Python, 42

    c=""
    i=input
    exec'c+=" "*i();'*i()
    print len(c)
    

    Coding man

    Posted 2011-02-24T09:59:28.223

    Reputation: 1 193

    This is a pretty smart solution. FWIW, I think the \n should count as two characters, as that's what it is in your source code before being executed. – mackthehobbit – 2014-03-05T11:07:02.737

    0

    Windows Batch, 68 (characters >= 32)

    I was about to post an extremely simple solution, but then I realised you have to read the number of test cases. Initially I just had for %%a in (%*)do set/a"i+=%%a" echo %i%.

    set/p t=
    for /l %%i in (1 1 %t%)do call :a
    echo %i%
    :a
    set/p N=
    if %n% geq 0 set/a"i+=N"
    

    It reads t, then each N from stdin.

    mackthehobbit

    Posted 2011-02-24T09:59:28.223

    Reputation: 314

    0

    J - 22 char

    All these inputs blowing up the character count. Envious of APL here...

    +/0>.".1!:1#&1".1!:1]1
    

    Explained:

    • 1!:1]1 - Read in a line of input (1!:1) from input (file handle 1).
    • #&1". - Convert to an integer (".) and create a list of 1s that long (#&1).
    • ".1!:1 - Read in a line for each 1 in the list, and convert them to integers.
    • 0>. - Take the greater of each integer and 0, effectively zeroing the negative numbers.
    • +/ - Sum all the integers together.

    Usage:

       +/0>.".1!:1#&1".1!:1]1
    3
    11
    909
    -67
    920
    

    algorithmshark

    Posted 2011-02-24T09:59:28.223

    Reputation: 8 144

    You can use echo for the output. – FUZxxl – 2015-07-19T11:59:06.870

    0

    K - 20 char -2 = 18 pts

    Had two 20 char solutions, and this one has more whitespace.

    (. 0:`){x+0|. 0:`}/0
    

    Explained:

    • n f/0 - Apply the function f to 0, n times.

    • (. 0:`) - Read in a line (0:) from input (file handle `) and convert to integer (.).

    • {x+0|. 0:`} - Read in an integer (. 0:`), take the greater of it and zero (0|), and add it to the argument (x+).

    Usage:

      (. 0:`){x+0|. 0:`}/0
    4
    123
    -99
    12
    9
    144
    

    algorithmshark

    Posted 2011-02-24T09:59:28.223

    Reputation: 8 144

    0

    JavaScript 93

    Works for t integers, but said integers need to be entered with spaces in between.

    y=(x=prompt().replace(/-\d{1,4}/g,"").replace(/ /g,"")).length;for(s=0;y--;)s+=+x[y];alert(s)

    Takes the prompt, strips negative numbers and spaces, and adds the numbers...

    WallyWest

    Posted 2011-02-24T09:59:28.223

    Reputation: 6 949

    0

    C

    void main()
    {
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
         {
         if(i>0)
         sum=sum+i;
         }
    printf("sum of positive numbers is %d",sum);
    }
    

    sanchita sangiri

    Posted 2011-02-24T09:59:28.223

    Reputation: 1

    Added language name. There's a lot of room for reductions here - sum can be reduced to s, the output string can just be "%d", etc. – Gareth – 2012-10-31T09:17:02.347

    1Welcome to CodeGolf.SE! If you look at the other answer, you'll see that they have formatted code and a minimal header noting the implementation language; on more complicated challenges many also have notes on the implementation and any limits or surprises in the code. Without some of this, you answer is unlikely to be well received. – dmckee --- ex-moderator kitten – 2011-10-12T15:28:13.237

    I counted the chars, added the indentation to make code-layout work, and removed the decoration of the output. Oh - now I have to count again. :) – user unknown – 2011-10-13T14:35:53.587

    0

    scala 55 54:

    println ((for (r <- 1 to readInt;
      i=readInt;
        if i>0) yield i)sum)
    

    user unknown

    Posted 2011-02-24T09:59:28.223

    Reputation: 4 210

    0

    C++:

    #include<iostream>
    using namespace std;
    int main()
    {
        int c,n,s=0;cin>>c;
        while(c--)
        {
            cin>>n;s+=n*(n>0);
        }
    cout<<s;return 0;
    }
    

    115 characters long. Need to optimize it to 90. Any suggestions ?

    CodeJunkie

    Posted 2011-02-24T09:59:28.223

    Reputation: 1

    2Just the standard tricks: The return is unnecessary in standard C++ or C99, there is an implicit return 0 in main. By making the variables global you can drop the =0 initialization. Finally, for(;;) is the same number of characters as while() but you get two extra places to put an expression in. – han – 2012-03-25T11:10:34.583

    This is already old, but also, writing std:: before cin and cout and getting rid of the using namespace std; can save 5 more characters. – Morwenn – 2013-07-03T11:35:57.137

    0

    Pyth - 7

    Input in pyth is only one line, so it accepts comma-delimited instead of newline delimited. Pyth is not on Spoj, but there wasn't any rule saying it had to be.

    sf>TZtQ
    

    Very simple:

    s      sum
    f      filter by
    >TZ    filter arg greater than zero
    tQ     run filter on all but first element of evaluated input
    

    Maltysen

    Posted 2011-02-24T09:59:28.223

    Reputation: 25 023

    0

    C#, score: 174

    using System;
    
    class P
    {
        static void Main(string[] a)
        {
            uint s = 0, t, n;
            for (uint.TryParse(Console.ReadLine(), out t); t-- > 0; uint.TryParse(Console.ReadLine(), out n), s += n) ;
            Console.WriteLine(s);
        }
    }
    

    RomSteady

    Posted 2011-02-24T09:59:28.223

    Reputation: 127

    0

    C, 60 characters

    There doesn't seem to be much to improve.

    c;
    
    main(x)
    {
        while (0 < scanf("%d", &x))
            c += x * (x > 0);
    
        printf("%d", c);
    }
    

    FUZxxl

    Posted 2011-02-24T09:59:28.223

    Reputation: 9 656

    0

    PHP, 71

    <?for($s=0,$t=fgets(STDIN)+0;$t--;$s+=($n=fgets(STDIN))>0?$n:0);echo$s;
    

    l0n3sh4rk

    Posted 2011-02-24T09:59:28.223

    Reputation: 1 387

    0

    Python: (92 characters)

    t = int(raw_input())
    n = [int(raw_input()) for i in range(t)]
    print(sum([n[i] for i in range(t) if n[i]>0]))
    

    Rushil Paul

    Posted 2011-02-24T09:59:28.223

    Reputation: 251

    Using a=raw_input and r=range and using a() and r() later can save quite a few characters. – Morwenn – 2013-07-03T11:37:31.910

    0

    C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace ConsoleApplication1
    {
     static class Program
     {
       static void Main(string[] args)
       {
         Console.WriteLine(Console.In.ReadToEnd().Split('\n').Sum(l => { Int32 v; return Int32.TryParse(l, out v) ? v.To(1000).Where(x => x > 0).Sum() : 0; }));
    
        }
        static IEnumerable<int> To(this int a, int b) { for (var i = a; a <= b; a++) { yield return i; } }
      }
    }
    

    Adam Speight

    Posted 2011-02-24T09:59:28.223

    Reputation: 1 234

    0

    Factor, 95 bytes

    [ [ readln dup string>number ] [ string>number dup [ 2 * ] [ ] if ] produce [ 0 max ] map sum ]
    

    Like a lambda; use it with call.

    cat

    Posted 2011-02-24T09:59:28.223

    Reputation: 4 989

    0

    Ruby, 42

    s=0
    gets.to_i.times { 
        i=gets.to_i
        s+=i if i>0
    }
    p s
    

    (based on david4dev's answer)

    Best score for Ruby on spoj: http://www.spoj.com/ranks/SIZECON/lang=RUBY

    Fábio Perez

    Posted 2011-02-24T09:59:28.223

    Reputation: 161

    -1

    C++ (96 points)

    #include<iostream>
    main()
    {
    int t,n,s=0;
    for(std::cin>>t;t;std::cin>>n, --t, n>0?s+=n:s);
    std::cout<<s;
    }
    

    Anurag Aryan

    Posted 2011-02-24T09:59:28.223

    Reputation: 101

    -1

    Python, 43

    c=0
    i=input
    exec'b=i();c+=b*(b>0);'*i()
    print c
    

    JeanClaudeDaudin

    Posted 2011-02-24T09:59:28.223

    Reputation: 231

    Please use code block formatting, so scripts like Code Golf UserScript Enhancement Pack can insert the code block length.

    – manatwork – 2015-07-19T11:20:53.970

    -1

    Python 52 Characters

    c = 0
    for i in range(t):
        k = input()
        if k>0:
            c+=k
    print c 
    

    rajasekhar vanjarapu

    Posted 2011-02-24T09:59:28.223

    Reputation: 1

    1Welcome to PPCG! It appears that neither spaces nor newlines should be included in the score, so I count your answer as 43, not 52. Also, it looks like three lines of your code are missing the indentation required by the for loop. – Martin Ender – 2015-09-24T10:58:27.197

    @MartinBüttner Thanks for the correction. When i submitted my code, 52 was what i saw. – rajasekhar vanjarapu – 2015-09-24T14:46:27.663