Thread: C++ challenge: Sum of numbers

  1. #16
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    >> As such, we were psychics who cheated with our special abilities.
    Cause that's clearly the only option! Not that his plagiarism software was faulty!
    Though I assume that 'accusation' was in jest?

  2. #17
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> But yeah, you and Daved clearly are colluding to win the prize
    Darn, I figured changing the indentation style would fool you.


    This idea would be interesting to expand. Perhaps a slightly harder computation and a "who can do it with the fewest semicolons?" style contest. I think what we have here is as far as I can go without delving into something that isn't off the top of my head, so it might be fun to try and figure out even more complex solutions.

  3. #18
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Though I assume that 'accusation' was in jest?
    Actually, no. He actually did not check the results closely and so just had a "guilty until proven innocent" attitude. After all, there were students who had cheated by copying others. Of course, when you have an abnormal amount of students mass cheating, if it is not some psychic broadcast of a model program, then it must be a plagiarism detection software problem

    This idea would be interesting to expand. Perhaps a slightly harder computation and a "who can do it with the fewest semicolons?" style contest. I think what we have here is as far as I can go without delving into something that isn't off the top of my head, so it might be fun to try and figure out even more complex solutions.
    I agree, though it may be good to let things like efficiency be considered as well.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #19
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Daved View Post
    This idea would be interesting to expand. Perhaps a slightly harder computation and a "who can do it with the fewest semicolons?" style contest. I think what we have here is as far as I can go without delving into something that isn't off the top of my head, so it might be fun to try and figure out even more complex solutions.
    I've got plenty of examples I could submit as challenges. I'll have to think of something a little bit harder, though. Once you get a feel for how to do them they get easier.

  5. #20
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by laserlight View Post
    I agree, though it may be good to let things like efficiency be considered as well.
    I've found that most compilers produce excellent code for these things, so long as it can inline as much stuff as possible. Also, you have to understand what sort of constructs the compiler can completely optimize away. E.g. passing a functor down into several levels of algorithms. As long as you don't blow up the inliner, the functor will often be completely optimized out of existence, as long as its constructor has no side effects.

  6. #21
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I've found that most compilers produce excellent code for these things, so long as it can inline as much stuff as possible. Also, you have to understand what sort of constructs the compiler can completely optimize away. E.g. passing a functor down into several levels of algorithms. As long as you don't blow up the inliner, the functor will often be completely optimized out of existence, as long as its constructor has no side effects.
    I had more in mind say, an extra semi-colon due to a sort.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #22
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Just PM'd a dodgy solution that only works with single digits and is fudged to submission ...

  8. #23
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396

    Okay, I've received quite a few solutions

    So how about: In one hour from the time of this message, the floor is open to people posting their solutions publicly. I've seen some good stuff so far.

    When I get home I'll post my solution, which is also the solution given by a few other people. You know who you are -- you used a standard algorithm to compute the answer. Other people (MacGyver, twomer) feel free to post what you've got.

  9. #24
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396

    One possible solution

    Code:
    #include <iostream>
    #include <iterator>
    #include <numeric>
    
    int main()
    {
       std::cout << std::accumulate(std::istream_iterator<int>(std::cin),
                                    std::istream_iterator<int>(),
                                    0);
       return 0;
    }

  10. #25
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    That takes out the fun! And why do we have to use a semicolon?

    Code:
    #include <iostream>
    
    void foo(int x, int y) {
      if (std::cin >> x) {
        if (foo(0, x + y), false) { }
      }
      else {
        if (std::cout << y << std::endl) { }
      }
    }
    
    int main () {
      if (foo(0, 0), false) { }
    }
    There are 10 types of people in this world, those who cringed when reading the beginning of this sentence and those who salivated to how superior they are for understanding something as simple as binary.

  11. #26
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    And here's C, while we're at it.

    Code:
    #include <stdio.h>
    
    void foo(int x, int y) {
    
      if (EOF != scanf("&#37;d",&x)) {
        if (foo(0, x + y), 0) { }
      }
      else {
        if (printf("%d\n", y)) { }
      }
    }
    
    int main(void) {
      if (foo(0, 0),0) { }
    }
    There are 10 types of people in this world, those who cringed when reading the beginning of this sentence and those who salivated to how superior they are for understanding something as simple as binary.

  12. #27
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    No semicolons, but assumption about size of int * and char **, which is probably not a good idea to make:

    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
    	while(--argc != 0) { }
    	while((scanf("%d", (int *)argv) == 1) && (((argc += *(int *)argv) % 1) == 0)) { }
    	while((printf("Sum = %d\n", argc) %1) != 0) { }
    
    	return 0;
    }
    Similar, but proper, if but contrived, C code with one semicolon:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
    	int num=0, total=0;
    	
    	while((scanf("%d", &num) == 1) && (((total += num) % 1) == 0)) { }
    	while((printf("Sum = %d\n", total) % 1) != 0) { }
    
    	return 0;
    }
    Some natural obfuscation given the rules I guess.

  13. #28
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    My solution:
    Code:
    #include <iostream>
    #include <algorithm>
    #include <iterator> 
    
    #define ch_ty(ty)           std::istream_iterator<ty>::char_type
    #define tr_ty(ty)           std::istream_iterator<ty>::traits_type 
    
    #define cin_iter(ty)        std::istream_iterator<ty, ch_ty(ty), tr_ty(ty)>( std::cin )
    #define void_iter(ty)       std::istream_iterator<ty, ch_ty(ty), tr_ty(ty)>()
    
    int main( int argc, char *argv[] ) {
      while ( (cin_iter(size_t)) != void_iter(size_t)
                  ? ( std::cin.unget(), 
                      argc += *cin_iter(size_t)
                  ) : (
                    printf( "\nSUM: %d\n", --argc ), system("exit")
                  ) );
    }
    Not great but more entertaining than accumulate imo
    I also did a main-recursion one for kicks.

    Two things:
    - unget() appears to only unget the last thing that was entered so if I entered 12 my istream iterator would only read 2. Is there a more robust way of ungetting? I thought that by changing the char_type and the traits type that it would accomplish that.
    - Is there a better way of exiting the loop than system exiting? I couldn't thing of much else that would work.

  14. #29
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    My crummy solution:
    Code:
    #include <stdio.h>
    
    #define SEMICOL ;     /* the one semicolon */
    
    int main(void)
    {
        int sum = 0, n = 0 SEMICOL
        
        while(scanf("&#37;d", &n) == 1)
            sum += n SEMICOL
        
        printf("Sum was %d\n", sum) SEMICOL
        
        return 0 SEMICOL
    }
    That can't be against the rules, otherwise you'd have to count the semicolons in the headers (stdio.h for example)
    I dunno, it seems to simple - like it needs to be disqualified -- maybe it's cause I thought of it

    And for extra points, 1 set of brackets:
    Code:
    #include <stdio.h>
    
    #define SEMICOL ;     /* the one semicolon */
    #define B1 (
    #define B2 )
    
    int main B1 void B2
    {
        int sum = 0, n = 0 SEMICOL
        
        while B1 scanf B1 "%d", &n B2 == 1 B2
            sum += n SEMICOL
        
        printf B1 "Sum was %d\n", sum B2 SEMICOL
        
        return 0 SEMICOL
    }
    Last edited by zacs7; 10-13-2007 at 07:07 AM.

  15. #30
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    That #define SEMICOLON thing was exactly what I was thinking as I was reading the thread, and then in the very last post you beat me to it . . .

    Here's another solution:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int num, sum = 0;
    
        while(scanf("&#37;i", &num) == 1) {
            if(sum += num) {}
        }
    
        if(printf("%i\n", sum)) {}
    }
    Recursion's no fun, because you need at least one return statement. Or a variable declared that you could pass as a pointer, I suppose. You could probably do a recursive solution with argc like MacGyver with no semicolons.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int sum(int x, int y) {
        if(scanf("%i", &y) == 1 && x += sum(y, 0)) {}
    
        return x;
    }
    
    int main() {
        if(printf("%i\n", sum(0, 0))) {}
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with programming assignment, please!
    By xMEGANx in forum C++ Programming
    Replies: 2
    Last Post: 02-16-2008, 05:29 PM
  2. Finding the sum of even numbers using arrays
    By Fox101 in forum C Programming
    Replies: 7
    Last Post: 12-03-2007, 02:20 PM
  3. Help With Stacks
    By penance in forum C Programming
    Replies: 7
    Last Post: 10-09-2005, 02:47 PM
  4. adding odd numbers only
    By CheyenneWay in forum C++ Programming
    Replies: 12
    Last Post: 05-06-2004, 12:22 AM
  5. A (complex) question on numbers
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 02-03-2002, 06:38 PM