COME ON CODE ON

A blog about programming and more programming.

Size Contest

with 7 comments

Looks like i am having some affair with shorter codes. Anyways, there is this question on SPOJ. You have to write the shortest code for finding the sum of all positive integers,given a set of T integers followed by T.

As always i am far away from optimal result :

#include"iostream"
int a,t,s;
main()
{
      for(std::cin>>t;t--;std::cin>>a,s+=a>0?a:0);
      std::cout<<s;
} 
&#91;/sourcecode&#93;
And Python Solution :
&#91;sourcecode language='python'&#93;t=input()
s=0
while t:
    x=input()
    s+=x*(x>0)
    t-=1
print s

If you have a shorter C++ or Python code, help me out. Between try this line to see the path of your file.

printf("The source file name is %s\n",__FILE__);

-fR0D

Advertisements

Written by fR0DDY

February 17, 2009 at 5:18 PM

Posted in Beautiful Codes, Programming

Tagged with ,

7 Responses

Subscribe to comments with RSS.

  1. in place of comparing a>0, you can just check the sign bit. That will be a lot more optimized 🙂

    Akash

    May 19, 2009 at 1:13 PM

  2. how? Remember the aim is to minimize the size…

    fR0D

    May 19, 2009 at 1:17 PM

  3. # #include”iostream”
    # int a,t,s;
    # main()
    # {
    # for(std::cin>>t;t–;std::cin>>a,s+=(a>>31)?0:a);
    # std::cout<<s;
    # }

    it won’t reduce size but obviously optimize the cose in same size.

    PS: assumed 32 bit int.

    Akash

    May 19, 2009 at 1:39 PM

  4. #include
    you can use this header file and remove std::

    Sudhakar

    December 11, 2009 at 11:38 AM

  5. Correction in previous comment
    #include”rope.h”
    you can use this header file and remove std::

    Sudhakar

    December 13, 2009 at 1:14 PM

  6. Instead of:
    s+=a>0?a:0

    u can write
    s+=a>?0

    Boris

    October 23, 2010 at 10:37 PM

  7. A shorter python code… 42chars only
    s=0
    i=input
    exec(“s+=max(0,i());”)*i()
    print s

    mohanasudharsan

    December 21, 2012 at 11:11 PM


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: