tags:

views:

1071

answers:

6
+2  Q: 

Shortest code in C

Problem Statement : Sum the positive values in a series of integers.

Input :

t – number of test cases [t < 1000]. On each of next t lines given a integer N [-1000 <= N <= 1000]

Output :

One integer equals to sum of all positive integers.

This is actually a SPOJ problem.I had solved it using python & ruby already but now I am interested it solving it in C.

Here is my solution :

   a,s;
  main(n){
     for(scanf("%d",&a);
        a--;
        scanf("%d",&n),
        s+=(n>0)*n);
     printf("%d",s);
  }

My solution uses 79 characters.But in the best solution list there are people who solved them in 70 characters and 75 characters.So I want to know how such compaction is achieved ?

+3  A: 

maybe

    #define p ("%d",
    #define f scanf p &

       a,s;
     main(n){
     for(f a);
        a--;
        f n),
        s+=(n>0)*n);
     printf p s);
     }

if my math is right, saves a couple bytes.

sorry people, my mathematics is bad. I counted, it's actually worse.

aaa
nope, 80 bytes in total.
Nick D
you should also add `#define`'s characters. `#define` isn't white space, it's part of the language / program.
Nick D
89 significant chars. Getting worse and worse.
KennyTM
#define x a,s;main(n){for(scanf("%d",a--;scanf("%d",printf("%d",} x Two lines.
Austin Kelley Way
A: 

Edit: The following answer was posted before the question was tagged as "code golf" and before the meaning of the "code golf" tag was made apparent. I still stand by my answer as the original question was posted as a real world problem. Such questions and their solution then are only useful as intellectual exercises.

Is the shortest number of characters a useful metric?

This is the sort of "what does this piece of code do" question that excites people who aren't involved in writing maintainable code.

As an intellectual exercise it is quite interesting, but as a way of writing code that will eventually be maintained by others it is a questionable practice.

Previously, when various resources were rare, this was a legitimate concern. See Steven Levy's great book "Hackers" for discussions about the early days of the coding, e.g. at the MIT model railroad club, where such things were critical because of the limited resources on the machines that were available. So they finished up measuring cool code with such metrics and number of statements or the length of the paper tape containing your solution to an algorithm.

BTW The Hackers book has nothing to do with the fun 1995 movie of the same name. That is, apart from the title itself.

Well, let me explain the New World Order. Governments and corporations need people like you and me. We are Samurai... the Keyboard Cowboys... and all those other people who have no idea what's going on are the cattle... Moooo.

But given a modern machine, with vastly increased resources available, such things don't count as much any more.

We definitely should be aware of squandering resources. But we're not hamstrung by a lack of available resources as the early dev's were.

Densely packed code that is written to show off to other people no longer has a place in useful software development. It is just sowing "time bombs" for later detonation by those who aren't as "brilliant" as the original author thought he was.

As Damian Conway wrote in his excellent book "Perl Best Practices":

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."

I couldn't put it better than that if I tried. (-:

Rob Wells
Code Golfing is more for fun than any practical purpose. It's a test of one's code ingenuity and tests your knowledge of a language to its very limits in finding the most byte-friendly version of your code.It has no real practical purpose.
Xorlev
And the use in the real world? Minimal!
Rob Wells
Real world use: stress relief. :) It's good to take a breather. CG problems are popular on SO.
Xorlev
Since I, myself, have no practical purpose -- I must call you an insensitive clod.
Tim Post
"An insensitive clod"? Bit of an over reaction there. Especially since the question wasn't tagged as code golf when it was originally asked.
Rob Wells
@Rob Wells Since it is now tagged code-golf, you might consider deleting it. Though your answer is fine if this question was concerned with real-world code, it is now inappropriate.
ntownsend
@Xorlev, Harddrive space doesn't grow on trees you know :p
gnibbler
A: 

This version produces even more warnings, but it is 2 characters shorter than your version:

a,s,t = "%d";
main(n){
    for(scanf(t,&a);
        a--;
        scanf(t,&n),
        s+=(n>0)*n);
    printf(t,s);
}
quinmars
+2  A: 
  • no need to keep count; scanf returns 0 or EOF if you're done
  • scanf() can suppress assignment: scanf("%*d");
  • main() doesn't need to take an argument (we've optimized out n)

74 chars:

a,s;main(){for(scanf("%*d");scanf("%d",&a)>0;s+=a>0?a:0);printf("%d",s);}
Potatoswatter
well, that program works different. You have to type ^D manually to stop it, although you insert the count of numbers before.
quinmars
ah, i was assuming the input was a file.
Potatoswatter
SPOJ would reject your code: `crashed with Runtime Error: NZEC` (non zero exit code). I know because my 64 bytes solution was rejected with the same reason.
sambowry
I joined. The OP's given code does too. Needs `return`. Feh.
Potatoswatter
SPOJ is behaving strange with this problem,even my previously accepted code is giving Runtime Error: NZEC
nthrgeek
The recent changes in the judge makes it mandatory to use `return 0;`
nthrgeek
A: 

The new record is 68 :-)

My first version was a 122 long 'pedantic' code to test submission. After that i wrote a 89 long 'short' code, than i wrote many versions (1 or 2 chars shorter than the previous) until i reach 68.

sambowry
Please share your code.I will be honored to know how to write such a compact piece of code.
nthrgeek
You can not learn from results. But you can learn something if you must thinking, experimenting before the next result. Leave out some days if you have no idea how to continue.
sambowry
I was inquisitive to know whether you have used `return 0` or `exit(0)` anyways if you don't want to share then I didn't get the reason why you posted in this thread other than just boasting about one's knowledge ?:-)
nthrgeek
Depending on the current code i used return or exit until i reach 72. During this time i saw many times how my codes are running and what is the exit code if i don't use return/exit. I learn this way how i can set the exit code to any value without return/exit. So the <72 chars solutions does not contain return/exit but set the exit code to zero.
sambowry
I just want to learn that,but after series of serious attempts I am unable to figure out how to set the exit code to zero,I am using windows,so could you please help me in this regard,as far as the points is considered I have scored better in other languages,but I seriously want to konow how to ensure the exit status without explicit return 0 or exit(0).Any pointers in this regard will be very helpfull :)
nthrgeek
A: 

152 (necessary) characters

Obviously not the best solution, so I crushed it into a cube:

main(c,i,t,s,a){for
(t=i=2,s=a=0;t>1|i;
t=t?c>47?a*=10,a+=c
-48,t:(i=(t<2?s+=a,
i-1:a),a=0,1-(c==45
)):!c){c=getchar();
c*=c>47&c<58|c==45;
}printf("%d\n",s);}

I tried out a state machine design to avoid having to use scanf, but as we can see it needs more work. Here's the unobfuscated version:

#include <stdio.h>

enum {IGNORE, ACCEPT, COUNT}; // state
enum {DIGIT, MINUS, OTHER}; // parsed character (p)

int main(void)
{
 int c, p;
 int count;
 int state = COUNT;
 int sum = 0, current = 0;

 for (;;) {
  c = getchar();
  p = c>='0' && c<='9' ? DIGIT
    : c=='-' ? MINUS
    : OTHER;

  if (state == ACCEPT || state == COUNT) {
   if (p == DIGIT) {
    current *= 10;
    current += c-'0';
   } else {
    if (state == ACCEPT)
     sum += current;
    else {
     count = current;
     state = ACCEPT;
    }
    if (!count--)
     break;
    current = 0;
    if (p == MINUS)
     state = IGNORE;
   }
  } else { // IGNORE
   if (p == OTHER)
    state = ACCEPT;
  }
 }

 printf("%d\n", sum);
 return 0;
}

I'm sure a more impressive score can be attained with this approach, but I have better things to do.

Joey Adams
A cube is 3 dimensional. This is a rectangle. ;)
KennyTM
I don't think C really cares :P
Joey Adams