The Daily WTF: Curious Perversions in Information Technology
Welcome to TDWTF Forums Sign in | Join | Help
in Search

Outputting Number Sequences

Last post 05-11-2007 3:51 PM by Random832. 101 replies.
Page 1 of 3 (102 items) 1 2 3 Next >
Sort Posts: Previous Next
  • 05-22-2006 1:50 AM

    Outputting Number Sequences

    Here's a fun puzzle. This is another one for the language lawyers out there. Few if any practical applications I can see.

    Write a program that prints all the numbers from 0 to 100.

    But, following the following restrictions (in what I think is increasing difficulty; the restrictions may give away answers, and at least provide substantial clues). 

    1. Don't use any loops (for and while are out) or if statements

    2 [highlight]. Don't use any ?: operators

    3. Don't use short circuit evaluation

    4. Don't use anything that you think will be compiled into object code that includes conditional branches, to the best of you ability (e.g. if cout << "Hello world"; has branches, don't worry about the equivalent in your program, but you should't introduce any others)

    The general idea is to come up with as many ways to to this as possible, besides just printf("0 1 ... 100");. I personally know of four completely different approaches. Two are standard C, one is standard C++, and one is non-standard (but still somewhat reasonable) C++. (I forget what compilers the last works under, but at least GCC.)

    I dunno, maybe this is well known; I originally saw it on a /. post. If so, sorry for the dupe.

  • 05-22-2006 2:48 AM In reply to

    • ammoQ
    • Top 10 Contributor
    • Joined on 04-13-2005
    • Vienna.Austria.Europe.Earth
    • Posts 3,444

    Re: Outputting Number Sequences

    #include <stdio.h>

    int count(int n) {
            printf("%d ", n);
            fflush(stdout);
            int x=1/(100-n);
            count(n+1);
    }

    int main() {
            count(0);
    }

    beanbag girl 4ever
  • 05-22-2006 3:29 AM In reply to

    • ammoQ
    • Top 10 Contributor
    • Joined on 04-13-2005
    • Vienna.Austria.Europe.Earth
    • Posts 3,444

    Re: Outputting Number Sequences

    #include <stdio.h>

    int (*f[2])();

    int count(int n) {
            printf("%d ", n);
            int x=n/100;
            f[x](n+1);
    }

    int donothing(int n) {
    }

    int main() {
            f[0]=count;
            f[1]=donothing;
            count(0);
    }

    beanbag girl 4ever
  • 05-22-2006 5:05 AM In reply to

    Re: Outputting Number Sequences

    ammoQ:
    #include <stdio.h>

    int count(int n) {
            printf("%d ", n);
            fflush(stdout);
            int x=1/(100-n);
            count(n+1);
    }

    int main() {
            count(1);
    }



    Recursion: poor man's loop. :D
    — Flurp.
  • 05-22-2006 5:26 AM In reply to

    • ammoQ
    • Top 10 Contributor
    • Joined on 04-13-2005
    • Vienna.Austria.Europe.Earth
    • Posts 3,444

    Re: Outputting Number Sequences

    I guess you have not dived too deep into the theoretical parts of CS, because otherwise you would know that loops are poor man's recursion.
    beanbag girl 4ever
  • 05-22-2006 10:43 AM In reply to

    • Zlodo
    • Top 500 Contributor
    • Joined on 12-08-2005
    • Posts 96

    Re: Outputting Number Sequences

    Both recursion and loop are poor man's copy-paste.
  • 05-22-2006 1:59 PM In reply to

    Re: Outputting Number Sequences

    dhromed:
    ammoQ:
    #include <stdio.h>

    int count(int n) {
            printf("%d ", n);
            fflush(stdout);
            int x=1/(100-n);
            count(n+1);
    }

    int main() {
            count(1);
    }



    Recursion: poor man's loop. :D
    Quite the opposite, and the reason why Scheme (for example) has no loops (you don't need them in the first place)
    "Well, take it from an old hand: the only reason it would be easier to program in C is that you can't easily express complex problems in C, so you don't." - Erik Naggum (in comp.lang.lisp)
  • 05-22-2006 5:22 PM In reply to

    • Silex
    • Not Ranked
    • Joined on 11-29-2004
    • Posts 15

    Re: Outputting Number Sequences

    Here's my attempt :)

    #include <iostream>

    template <int min, int max>
    struct range_printer
    {
        static void print()
        {
            std::cout << min << ' ';
            range_printer<min + 1, max>::print();
        }
    };

    template <int finished>
    struct range_printer<finished, finished>
    {
        static void print()
        {
            std::cout << finished << std::endl;
        }
    };

    int main()
    {
        range_printer<0, 100>::print();
        return 0;
    }
  • 05-23-2006 8:32 PM In reply to

    Re: Outputting Number Sequences

    First I thought this was a complete challenge, but I realized Java is not a valid language.

    Here's one approach, completely outside the spirit of the rules:

    void do(int i)
    {
        int j = 1 / (101 - i)
        printf("%d",i);
       do (i + 1);
    }

    void main()
    {
        do(0);
    }

    It's somewhate reasonable. It DOES print the variables, but causes a crash afterwards. Unfortunately, it uses function calls, so compiles with branches.

    EDIT: Oh, someone beat me.
  • 05-24-2006 12:39 AM In reply to

    Re: Outputting Number Sequences

    akrotkov:
    First I thought this was a complete challenge, but I realized Java is not a valid language.


    Hey, I'm thinking C and C++, but if you've got a solution in Java that'd be fine too.

    Actually, at least two of the solutions would work fine in Java. The divide by zero case probably does work (or at least if you modify it right), though I don't know Java well enough to know.

    Here's one approach, completely outside the spirit of the rules:

    (snip)

    It's somewhate reasonable. It DOES print the variables, but causes a crash afterwards. Unfortunately, it uses function calls, so compiles with branches.


    If it crashes, I think that's a no-no, but at least with some compilers and C++ you can make it not crash. Under MSVC, floating point divide by zero throws an exception; this exception can be caught in main and ignored.  (This is the modification I have for the Java solution.) I *think* I tried it under GCC and got the same behavior.

    Finally, the function call branches are absolutely allowed because they are unconditional. I really have no clue how exceptions are compiled (my compiler course was horrible and I haven't looked into it myself) so don't know if they are done with branches or some other tricks internally; of course, it might differ by platform. But it's conceivable to me that at least this code might not have any conditional branches in the program itself.


    Anyway, to address the other solutions, looks good. You can highlight #2 and 3 in my original post (especially 3) for the other solutions I know of.

    (If you have any more, I'd love to see them!)
  • 05-24-2006 5:14 AM In reply to

    • Silex
    • Not Ranked
    • Joined on 11-29-2004
    • Posts 15

    Re: Outputting Number Sequences

    Here's my 2nd attempt.

    Something tells me you didn't think of this one :)
    Note all resolves to a single stirng output, so it's pretty optimized :P

    #include <iostream>

    using namespace std;

    #define INC_0 1
    #define INC_1 2
    #define INC_2 3
    #define INC_3 4
    #define INC_4 5
    #define INC_5 6
    #define INC_6 7
    #define INC_7 8
    #define INC_8 9

    #define INC(i) INC_I(i)
    #define INC_I(i) INC_ ## i

    #define STR(text) STR_I(text)
    #define STR_I(text) #text

    #define BUILD(prefix, i) STR(prefix) STR(i) " "
    #define BUILD_TWO(prefix, i) BUILD(prefix, i) BUILD(prefix, INC(i))
    #define BUILD_FOUR(prefix, i) BUILD_TWO(prefix, i) BUILD_TWO(prefix, INC(INC(i)))
    #define BUILD_TEN(prefix) BUILD_FOUR(prefix, 0) BUILD_FOUR(prefix, 4) BUILD_TWO(prefix, 8)
    #define BUILD_TWENTY(prefix) BUILD_TEN(prefix) BUILD_TEN(INC(prefix))
    #define BUILD_FORTY(prefix) BUILD_TWENTY(prefix) BUILD_TWENTY(INC(INC(prefix)))
    #define BUILD_0_100 BUILD_TEN() BUILD_FORTY(1) BUILD_FORTY(5) BUILD_TEN(9) "100"

    int main()
    {
        cout << BUILD_0_100 << endl;
        return 0;
    }
  • 05-24-2006 10:48 AM In reply to

    • iwpg
    • Top 150 Contributor
    • Joined on 05-24-2006
    • Posts 258

    Re: Outputting Number Sequences


    #include <stdio.h>
    #include <stdlib.h>

    static int x[(1 << 10) - 1];
    static int n = 0;

    static int
    callback2(const void *a, const void *b)
    {
        printf("%d ", n++);
        return 1;
    }

    static int
    callback1(const void *a, const void *b)
    {
        bsearch(x, NULL, sizeof(x) / sizeof(x[0]), sizeof(x[0]), callback2) ;
        return 1;
    }

    int
    main(void)
    {
        bsearch(x, NULL, sizeof(x) / sizeof(x[0]), sizeof(x[0]), callback1);
        printf("100\n");
        return EXIT_SUCCESS;
    }


    I'm not sure if it's OK to rely on bsearch() calling the callback a certain number of times, but it works under Solaris.... ;-)

    (ObPleaToTheForumGods: please please please don't mangle my first post!)
  • 05-25-2006 9:54 AM In reply to

    Re: Outputting Number Sequences

    As this seems to be a challenge in obfuscating conditional and repetitive code execution and this brain of mine feels quite insomniacish: Let there be Python and horrible misusage of regular expressions!
    import re
    from string import digits   # digits=='0123456789' (except for the roman empire)
    narf = re.compile(r'(\d)')
    poit = narf.sub(r' \\g\g', digits)    #\g is a backreference to group n
    zort = narf.sub(poit, digits)
    print zort.replace(' 0',' ').lstrip() + " 100"
    fun fun, silly willy
    Up and let's goto!
  • 05-25-2006 10:02 AM In reply to

    Re: Outputting Number Sequences

    ARGH. and now with all chars included:
    import re
    from string import digits   # digits=='0123456789' (except for the roman empire)
    narf = re.compile(r'(\d)')
    poit = narf.sub(r' \\g<1>\g<1>', digits)    #\g<n> is a backreference to group n
    zort = narf.sub(poit, digits)
    print zort.replace(' 0',' ').lstrip() + " 100"
    Up and let's goto!
  • 05-26-2006 3:01 AM In reply to

    Re: Outputting Number Sequences

    #! /usr/bin/perl
    $Num=1;
    $ThisFile = "1to100.pl";
    print $Num . "\n";
    if($Num==100) {$Num=0}
    open(FILEIN, "< $ThisFile");
    @FILECONT = <FILEIN>;
    $ThisFileText = join "", @FILECONT;
    close(FILEIN);
    $NewText =
        substr($ThisFileText, 0, index($ThisFileText, "\$Num")+5) . ($Num+1) . ";\n" .
        substr($ThisFileText, index($ThisFileText, "\$ThisFile"));

    open(FILEOUT, "> $ThisFile");
    print FILEOUT $NewText;
    close(FILEOUT);
    if($Num) {exec "./".$ThisFile}


    I'd do the same thing in C, but I have no intention of breaking out the hex editor to do this.
  • 05-26-2006 5:50 AM In reply to

    • Shen
    • Not Ranked
    • Joined on 10-25-2005
    • Posts 23

    Re: Outputting Number Sequences

    Untested. Not sure if you can catch sigsegv like this, but I'm trying anyway :p

    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>

    #define limit 100
    void wtf(int n);
    void end(int sig);
    int *nums;

    int main()
    {
      signal(SIGSEGV, end);
      nums = malloc(limit * sizeof(int));
      wtf(0);
      free(wtf); /* for completeness ;) */
      return 0;
    }

    void wtf(int n)
    {
      printf("%d\n", n);
      int useless_value = nums[n];
      wtf(++n);
    }

    void end(int sig)
    {
      exit(EXIT_SUCCESS); /* silly thing is, it isn't */
    }

  • 05-26-2006 7:37 AM In reply to

    • iwpg
    • Top 150 Contributor
    • Joined on 05-24-2006
    • Posts 258

    Re: Outputting Number Sequences

    Shen:
    Untested. Not sure if you can catch sigsegv like this, but I'm trying anyway :p
    [snip]

    That goes up to 3422 for me before it stops, when compiled without optimisation - you can't be sure that malloc() won't allocate more memory than you ask for.  Also, the assignment to useless_value gets optimised away completely with optimisation on, so it runs forever.  Not a bad idea, though.  I did try to come up with something using SIGSEGV, but I couldn't think of anything reliable or portable enough, although I probably shouldn't complain about such things after horribly abusing bsearch().

    Anyway, I have a couple more along similar lines:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <signal.h>
    
    void
    handler(int bleh)
    {
        exit(EXIT_SUCCESS);
    }
    
    void
    loop(int n)
    {
        printf("%d\n", n);
        sleep(2);
        loop(n + 1);
    }
    
    int
    main(void)
    {
        signal(SIGALRM, handler);
        alarm(201);
        loop(0);
        return EXIT_SUCCESS; /* not reached */
    }
    

    and

    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>
    
    void
    handler(int bleh)
    {
        exit(EXIT_SUCCESS);
    }
    
    void
    loop(int n, FILE *output)
    {
        fprintf(output, "%d\n", n);
        loop(n + 1, output);
    }
    
    int
    main(void)
    {
        FILE *output = popen("head -n 101", "w");
        signal(SIGPIPE, handler);
        loop(0, output);
        return EXIT_SUCCESS; /* not reached */
    }
    
  • 05-26-2006 1:56 PM In reply to

    • Shen
    • Not Ranked
    • Joined on 10-25-2005
    • Posts 23

    Re: Outputting Number Sequences

    iwpg:
    FILE *output = popen("head -n 101", "w");

    That's cheating! int main() { system("a"); } Have you not heard of my "a" program? Coincidentally, it prints the numbers from 0 to 100 just fine!

    Anyway. I can still do it backwards. Tested, works for me.

    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>

    #define limit 100
    #define offset 3
    void wtf(int n);
    void end(int sig);
    int *nums;

    int main()
    {
      signal(SIGSEGV, end);
      nums = malloc(limit * sizeof(int));
      wtf(limit - offset);
      free(wtf);
      return 0;
    }

    void wtf(int n)
    {
      printf("%d\n", limit - n - offset);
      int useless_value = nums[n];
      wtf(--n);
    }

    void end(int sig)
    {
      exit(EXIT_SUCCESS);
    }

  • 05-26-2006 2:40 PM In reply to

    • ammoQ
    • Top 10 Contributor
    • Joined on 04-13-2005
    • Vienna.Austria.Europe.Earth
    • Posts 3,444

    Re: Outputting Number Sequences

    I'm really surprised to see so many people using "signal" here. I considered using that for my "division-by-zero-exit" program, too, but then I though "No way, too many MS-focused people here, they would be unable to compile it".
    beanbag girl 4ever
  • 05-27-2006 8:58 AM In reply to

    • makomk
    • Top 100 Contributor
    • Joined on 09-03-2005
    • Not here
    • Posts 291

    Re: Outputting Number Sequences

    akrotkov:
    First I thought this was a complete challenge, but I realized Java is not a valid language.

    Here's one approach, completely outside the spirit of the rules:

    void do(int i)
    {
        int j = 1 / (101 - i)
        printf("%d",i);
       do (i + 1);
    }

    void main()
    {
        do(0);
    }

    It's somewhate reasonable. It DOES print the variables, but causes a crash afterwards. Unfortunately, it uses function calls, so compiles with branches.

    EDIT: Oh, someone beat me.
    Slight variation on this theme, inspired by a previous poster. The "volatile int" makes it work better if optimization is turned on, and the signal handling makes it exit cleanly (on some platforms, anyway - I don't think it'll always prevent the program from crashing).

    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>

    void wtf(int n);
    void end(int sig);

    int main()
    {
      signal(SIGFPE, end);
      wtf(0);
      return 0;
    }

    void wtf(int n)
    {
      volatile int dummy;
      printf("%d\n", n);
      dummy = 1 / (100 - n);
      wtf(n+1);
    }
    void end(int sig)
    {
      exit(EXIT_SUCCESS);
    }
    You know it's Enterprise Software when the vendor freebie is a red shirt.
  • 05-27-2006 8:57 PM In reply to

    • OpBaI
    • Top 500 Contributor
    • Joined on 10-09-2005
    • Posts 87

    Re: Outputting Number Sequences

    Are you paid by the line?
    
    #include <stdio.h>
    int finish(int n, char **p) {
        return !puts("");
    }
    int main(int n, char **p) {
        static int (*f[2]) (int, char **) = { main, finish };
        printf("%d ", n-1);
        return f[n==101](n+1, 0);
    }
  • 05-27-2006 9:04 PM In reply to

    • OpBaI
    • Top 500 Contributor
    • Joined on 10-09-2005
    • Posts 87

    Re: Outputting Number Sequences

    Two lines less:
    
    #include <stdio.h>
    #define P printf("%d ", n++ - 1)
    #define Q P;P;P;P;P;P;P;P;P;P
    #define R Q;Q;Q;Q;Q;Q;Q;Q;Q;return !puts("")
    int main(int n, char **p) {
        P;Q;R;
    }
    
  • 05-28-2006 5:04 AM In reply to

    Re: Outputting Number Sequences

    Similar technique to Silex above:

    #include <cstdio>
    template<int i>void p(){p<i-1>();printf("%d ",i);}template<>void p<0>(){}int main(){p<100>();}

  • 05-30-2006 9:54 PM In reply to

    Re: Outputting Number Sequences

    The key here is the *program* can't have any conditional branches or while loops...
    int main() { return system("for ((i=0; i<=100; i++)); do echo $i; done"); }

    Nothing says that the operating environment can't do the branching for you.
    The TDWTF Drinking Algorithm
    while (numDrinks < 3) {
    haveADrink();
    }
    gotoWork();
    while (numDrinks < 6) {
    haveADrink();
    }
    wasteMyTimeAndOthersOnTDWTF();
  • 06-02-2006 9:39 AM In reply to

    • DrPizza
    • Top 500 Contributor
    • Joined on 11-22-2004
    • Airstrip One, Oceania
    • Posts 107

    Re: Outputting Number Sequences

    #include <stdio.h>
    #include <stdlib.h>
    
    void foo(int i)
    {
        printf("%d ", ++i);
        ((void (*)(int))((size_t)(foo) + (((size_t)(exit) - (size_t)(foo)) & -(0 < i - 99))))(i);
    }
    
    int main()
    {
        foo(0);
    }
    

    Some arches may branch on the less than (including x86), but some (including MIPS, IA64 and ARM) can do the less than branchlessly, so it's good enough for me.

    I am not Gene Wirchenko
  • 06-02-2006 9:42 AM In reply to

    • DrPizza
    • Top 500 Contributor
    • Joined on 11-22-2004
    • Airstrip One, Oceania
    • Posts 107

    Re: Outputting Number Sequences

    And if we exploit the fact that 100 is the first three-digit number:

    #include <stdio.h>
    #include <stdlib.h>
    
    void foo(int i)
    {
        ((void (*)(int))((size_t)(foo) + (((size_t)(exit) - (size_t)(foo)) & -(0 < printf("%d ", ++i) - 3))))(i);
    }
    
    int main()
    {
        foo(0);
    }
    
    I am not Gene Wirchenko
  • 06-05-2006 7:21 PM In reply to

    • vIk34
    • Not Ranked
    • Joined on 06-05-2006
    • Posts 1

    Re: Outputting Number Sequences

    #include <stdio.h>
    int main(int argc) {
            static int (*f[2])(int) = { main, putchar }, i=101;
            printf("",f[i==0](0),printf("%i\n",101-i--));
    }

    dirty work ~
  • 06-05-2006 8:30 PM In reply to

    Re: Outputting Number Sequences

    #include <cstdlib>
    #include <iostream>
    #include <iterator>
    struct MyIt {
    public:
            typedef int value_type, difference_type;
            typedef MyIt *pointer, &reference;
            typedef std::input_iterator_tag iterator_category;
            int i;
            MyIt(int i = 0) : i(i) {}
            MyIt &operator++() { ++i; return *this; }
            bool operator!=(const MyIt &my) const { return i != my.i;}
            int operator*() { return i; }
    };

    int main() {
            std::copy(MyIt(0), MyIt(101), std::ostream_iterator<int>(std::cout, "\n"));
    }

    Although, I think std:copy DOES get compiled into branches. But its still an interesting answer I think.
  • 06-05-2006 8:34 PM In reply to

    Re: Outputting Number Sequences

    #include <iostream>

    bool print(int i) {
            std::cout << i << ' ';
            return i < 100 && print(i+1);
    }

    int main() {
            print(0);
    }

    Again. i <100 && print(i+1) will "branch", but not exactly.
  • 06-06-2006 10:53 PM In reply to

    • tster
    • Top 10 Contributor
    • Joined on 04-11-2006
    • Natick, MA
    • Posts 1,765

    Re: Outputting Number Sequences

    you might have to tweek NUMBER depending on your page size you set when you compiled the linux kernel....

    #include <signal.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #define NUMBER 83

    char *buffer;
    int ender;
    int start;

    void sigsegv(int i) {
        exit(0);   
    }

    void sigusr1(int i) {
        signal(SIGUSR1, sigusr1);
        printf("%i\n", start);
        char notUsed = buffer[ender];
        ender -= NUMBER;
        start++;
        kill(getpid(), SIGUSR1);
    }

    int main() {
        buffer = calloc ( 0 , sizeof (char));
        ender = 0;
        start = 1;
        signal(SIGUSR1, sigusr1);
        signal(SIGSEGV, sigsegv);
        kill(getpid(), SIGUSR1);
        return 0;
    }


    The pig go. Go is to the fountain. The pig put foot. Grunt. Foot in what? ketchup. The dove fly. Fly is in sky. The dove drop something. The something on the pig. The pig disgusting... see bio for the earth shattering ending.
  • 06-07-2006 12:07 PM In reply to

    Re: Outputting Number Sequences

    tster:
    you might have to tweek NUMBER depending on your page size you set when you compiled the linux kernel....


    Not if you do it THIS way:

    #include <signal.h>
    int start = 0, end = 101;
    void sigfpe(int i) { exit(0); }

    void sigusr1(int i) {
            int tmp = start/end--;
            signal(SIGUSR1, sigusr1);
            printf("%i\n", start++);
            kill(getpid(), SIGUSR1);
    }

    int main() {
            signal(SIGUSR1, sigusr1);
            signal(SIGFPE, sigfpe);
            kill(getpid(), SIGUSR1);
            return 0;
    }

  • 06-07-2006 5:36 PM In reply to

    • tster
    • Top 10 Contributor
    • Joined on 04-11-2006
    • Natick, MA
    • Posts 1,765

    Re: Outputting Number Sequences

    danielpitts:
    tster:
    you might have to tweek NUMBER depending on your page size you set when you compiled the linux kernel....


    Not if you do it THIS way:

    #include <signal.h>
    int start = 0, end = 101;
    void sigfpe(int i) { exit(0); }

    void sigusr1(int i) {
            int tmp = start/end--;
            signal(SIGUSR1, sigusr1);
            printf("%i\n", start++);
            kill(getpid(), SIGUSR1);
    }

    int main() {
            signal(SIGUSR1, sigusr1);
            signal(SIGFPE, sigfpe);
            kill(getpid(), SIGUSR1);
            return 0;
    }



    I can't believe I didn't think of that!  yes that's much much better.  anyways, I like this solution because there is no recursion and no chance of being compiled into branches.
    The pig go. Go is to the fountain. The pig put foot. Grunt. Foot in what? ketchup. The dove fly. Fly is in sky. The dove drop something. The something on the pig. The pig disgusting... see bio for the earth shattering ending.
  • 06-14-2006 5:29 PM In reply to

    • cf3
    • Not Ranked
    • Joined on 06-14-2006
    • Posts 12

    Re: Outputting Number Sequences

    #include <setjmp.h>
    #include <stdio.h>
    #include <stdlib.h>

    jmp_buf a;

    void b(int c)
    {
            printf("%d\n", c ^= 101);
            longjmp(a, ++c);
    }

    int main(void)
    {
            void (*d[])(int) = { b, exit };
            int e = setjmp(a);
            d[e / 101](e ^ 101);
    }

  • 06-16-2006 8:06 AM In reply to

    Re: Outputting Number Sequences

    Thought I'de join the fun with some Java code:

    package loopytest;
    public class TestApp implements Runnable
    {
    public static void main(String[] arg) throws Exception
    {
    // avoid stacktrace printing:
    System.setErr(null);
    // avoid crashing in main-thread:
    Thread t = new Thread(new TestApp());
    t.start();
    t.join();
    }

    public void run()
    {
    print(0);
    }

    void print(int i){
    System.out.println(i);
    int j = 1 / (100-i);
    print(i + 1);
    }
    }
    "All good software releases were accidents corrected in the next version."
    -- KattMan

    return paula;
  • 06-17-2006 1:00 PM In reply to

    • Katja
    • Top 100 Contributor
    • Joined on 11-29-2004
    • Amsterdam
    • Posts 298

    Re: Outputting Number Sequences

    No loops? No branching? Well, in some languages that means you must make sure a function gets called the exact amount of times. Something like this Delphi code:

    program Project2;

    {$APPTYPE CONSOLE}

    var
      Count: Integer = 0;

    procedure printOnes;
    begin
      WriteLn( Count );
      Inc( Count );
    end;

    procedure PrintTens;
    begin
      printOnes;
      printOnes;
      printOnes;
      printOnes;
      printOnes;
      printOnes;
      printOnes;
      printOnes;
      printOnes;
      printOnes;
    end;

    procedure PrintHundreds;
    begin
      PrintTens;
      PrintTens;
      PrintTens;
      PrintTens;
      PrintTens;
      PrintTens;
      PrintTens;
      PrintTens;
      PrintTens;
      PrintTens;
      printOnes; // We needed 101 values. :-)
    end;

    begin
      PrintHundreds;
      ReadLn;
    end.

    But it's real, real ugly. But in Pascal, the only way I can do this...

    With kind regards,
    X Katja Bergman.
  • 06-19-2006 8:54 AM In reply to

    Re: Outputting Number Sequences

    I call this "Stopping a Moving Vehicle Using A Brick Wall"

    var i = 100;
    var is = [];
    var output;

    function out() {
    is[i] = i;
    i--;
    out();
    }

    try {
    out();
    }
    catch (e) {
    output = is.join(',') + '\n';
    }

    alert(output);
    I'm uncertain as to whether I violate #4.
    — Flurp.
  • 06-20-2006 7:40 PM In reply to

    Re: Outputting Number Sequences


    #!/usr/bin/perl
    $wtf=0;
    sub wtf { print $wtf++,$/; }
    sub Wtf { wtf wtf }
    sub WTf { Wtf Wtf }
    sub WTF { WTf WTf WTf WTf WTf }

    WTF WTF wtf WTF WTF WTF

  • 06-30-2006 2:45 PM In reply to

    Re: Outputting Number Sequences

    I had an idea for this one in the shower the other day involving PHP's include() -- you can include the same file over and over again, and the code in it is executed every time.  As such, you can probably recursively include().

    That's the concept.  If anyone wants to take it and run, go for it.
  • 06-30-2006 3:45 PM In reply to

    Re: Outputting Number Sequences

    merreborn:
    I had an idea for this one in the shower the other day involving PHP's include() -- you can include the same file over and over again, and the code in it is executed every time.  As such, you can probably recursively include().

    That's the concept.  If anyone wants to take it and run, go for it.

    [ code ]
    <?php
        echo implode(' ',range(0,100));
    ?>
    [ /code ]
    probably branches and stuff, I had something nice with include() worked out, but it's hard to find something in PHP that actually throws an error, instead of a warning or just returning NULL.

    code tags eliminated cos they actually make it uglier (they insert &amp;nbsp; all over the place)
  • 06-30-2006 6:06 PM In reply to

    Re: Outputting Number Sequences

    AI0867:


    code tags eliminated cos they actually make it uglier (they insert &amp;nbsp; all over the place)


    The general fix for that is to prepare the spot where you want the code to be, then got into HTML mode and write <pre> tags with the code inside.

    HTML mode offers many things that the WIZZYWIG editor fucks up.
    — Flurp.
  • 07-02-2006 3:25 PM In reply to

    • iwpg
    • Top 150 Contributor
    • Joined on 05-24-2006
    • Posts 258

    Re: Outputting Number Sequences

    Since we're moving away from C:

    """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    
    Object subclass: #WTFInteger
           instanceVariableNames: ''
           classVariableNames: ''
           poolDictionaries: ''
           category: 'wtf?!?' !
    
    WTFInteger class methodsFor: 'wtfery' !
        wtf
            self asInteger printNl.
            ^self successor wtf !
    !
    
    WTFInteger class methodsFor: 'conversion' !
        asInteger
            ^self predecessor asInteger + 1 !
    !
    
    WTFInteger class methodsFor: 'arithmetic' !
        successor
            ^self subclassResponsibility !
        predecessor
            ^self subclassResponsibility !
    !
    
    """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    
    WTFInteger subclass: #Zero
               instanceVariableNames: ''
               classVariableNames: ''
               poolDictionaries: ''
               category: 'wtf?!?' !
    
    
    Zero class methodsFor: 'conversion' !
        asInteger
            ^0 !
    !
    
    Zero class methodsFor: 'arithmetic' !
        successor
            ^One !
        predecessor
            ^self shouldNotImplement !
    !
    
    """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    
    WTFInteger subclass: #OneHundredAndOne
               instanceVariableNames: ''
               classVariableNames: ''
               poolDictionaries: ''
               category: 'wtf?!?' !
    
    
    OneHundredAndOne class methodsFor: 'wtfery' !
        wtf
            ^nil !
    !
    
    OneHundredAndOne class methodsFor: 'arithmetic' !
        successor
            ^self notYetImplemented !
        predecessor
            ^OneHundred !
    !
    
    """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    
    WTFInteger subclass: #One
               instanceVariableNames: ''
               classVariableNames: ''
               poolDictionaries: ''
               category: 'wtf?!?' !
    One class methodsFor: 'arithmetic' !
        successor
            ^Two !
        predecessor
            ^Zero !
    !
    
    WTFInteger subclass: #Two
               instanceVariableNames: ''
               classVariableNames: ''
               poolDictionaries: ''
               category: 'wtf?!?' !
    Two class methodsFor: 'arithmetic' !
        successor
            ^Three !
        predecessor
            ^One !
    !
    
    WTFInteger subclass: #Three
               instanceVariableNames: ''
               classVariableNames: ''
               poolDictionaries: ''
               category: 'wtf?!?' !
    Three class methodsFor: 'arithmetic' !
        successor
            ^Four !
        predecessor
            ^Two !
    !
    
    "snip, you get the idea"
    
    WTFInteger subclass: #NinetyNine
               instanceVariableNames: ''
               classVariableNames: ''
               poolDictionaries: ''
               category: 'wtf?!?' !
    NinetyNine class methodsFor: 'arithmetic' !
        successor
            ^OneHundred !
        predecessor
            ^NinetyEight !
    !
    
    WTFInteger subclass: #OneHundred
               instanceVariableNames: ''
               classVariableNames: ''
               poolDictionaries: ''
               category: 'wtf?!?' !
    OneHundred class methodsFor: 'arithmetic' !
        successor
            ^OneHundredAndOne !
        predecessor
            ^NinetyNine !
    !
    
    """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    
    Zero wtf !
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    

    Ah, the power of OOP.... ;-)
  • 07-11-2006 8:29 PM In reply to

    Re: Outputting Number Sequences

    FYI, slightly more elegant way to build a string using the preprocessor:
    #include <iostream>
    #define A(p,s) \
       p B(0) s \
       p B(1) s \
       p B(2) s \
       p B(3) s \
       p B(4) s \
       p B(5) s \
       p B(6) s \
       p B(7) s \
       p B(8) s \
       p B(9) s
    #define C D( )D(1)D(2)D(3)D(4)D(5)D(6)D(7)D(8)D(9)

    #define B(a) #a
    #define D(a) A(#a,"\n")

    int main()
    {
       std::cout << C << "100" << std::endl;
    }


  • 07-25-2006 11:42 AM In reply to

    • dmwit
    • Not Ranked
    • Joined on 03-26-2006
    • Posts 4

    Re: Outputting Number Sequences

    How about Python?
    print range(101)
    EDIT: I guess this probably violates condition 4: don't emit any branches in the object code. =(
  • 07-26-2006 6:06 AM In reply to

    Re: Outputting Number Sequences

    format: .asciz "%u "
    addl $-8, %esp
    movl $0, 4(%esp)
    movl $format, (%esp)
    print: call printf
    movl 4(%esp), %eax
    incl %eax
    movl %eax, 4(%esp)
    jmp print



    of course, this doesn't end, but noone said it had to.
  • 08-08-2006 12:41 PM In reply to

    Re: Outputting Number Sequences

    Look Ma, no comparisons!
    Bit bloated.


    extern void exit(int);
    typedef void (*PF)(int);

    PF pf[101];

    void f(int i)
    {
            i++;
            printf("%d\n", i);
            pf[i] = f;
            pf[100] = exit;

            (*pf[i])(i);
    }

    int main(int argc, char *argv[])
    {
            f(0);
    }



  • 08-12-2006 10:28 AM In reply to

    Re: Outputting Number Sequences

    Its time to unleash this little bit of PHP(5) hell on the world:

    <?php

    function CountTo($Number) {
    $Length = StrLen($Number);
    $Regex = "/CountTo(0{0," . ($Length - 1) . "})/";

    // Create the autoload:
    Eval("function __autoload(\$Name) { echo Preg_Replace(\"$Regex\", Null, \$Name), \"\\n\"; \$Name++; return new \$Name(); }");

    // Create the object:
    Eval("class CountTo$Number { function __construct() { Exit(\"100\"); } }");

    // Start Counting:
    $Start = "CountTo" . Str_Repeat("0", $Length);
    new $Start();
    }

    CountTo(100);

    ?>

    Now I'll go kill myself for writing that ;)

  • 08-18-2006 10:21 AM In reply to

    • Blame
    • Not Ranked
    • Joined on 08-18-2006
    • Posts 2

    Re: Outputting Number Sequences

    I'm not sure whether this follows the rules properly, but I liked the idea, so had a go. :)
    #include "stdio.h"
    
    static int counter=0;
    class SomeObject
    {
    public:
      SomeObject(){printf("%d ",counter++);}
    };
    
    int main()
    {
      SomeObject ArrayOfThem[101];
      return 0;
    }
  • 08-23-2006 11:26 AM In reply to

    Re: Outputting Number Sequences

    Console.write("all the number from 0 to 100.");

    Trick question?

  • 08-27-2006 6:51 PM In reply to

    Re: Outputting Number Sequences

     I considered the same sort of idea :D

    in bash this works:

    tw@garden:~$ watch -t --interval=1 date +%S

    assuming you have your system setup to use 100 seconds per minute :D
    TRWTF is Community Server
  • 08-28-2006 12:57 PM In reply to

    • JCM
    • Not Ranked
    • Joined on 03-16-2006
    • Posts 23

    Re: Outputting Number Sequences

    I've not seen a .NET answer yet...  Since "if" is out, does that mean that "?" is out too?

    using System;

    namespace ConsoleApplication6
    {
        class Class1
        {
            [STAThread]
            static void Main(string[] args)
            {
                Counter x= new Counter(1);


                Console.WriteLine("\n\nPress [ENTER] to exit :)");
                Console.ReadLine();
            }
        }

        class Counter
        {
            public Counter(int count)
            {
                Console.Write("{0} ", count.ToString());

                Counter c= (count < 100) ? (new Counter(count+1)) : null;
            }
        }
    }


Page 1 of 3 (102 items) 1 2 3 Next >
Powered by Community Server (Non-Commercial Edition), by Telligent Systems