• Ben (unregistered) in reply to biff
    biff:
    index = selected;

    (It's ok. I don't need the money.)

    So if selected > 3 you'll set index to a value greater than 3? As opposed to the original code which set index to 0.

  • (cs) in reply to biff
    biff:
    index = selected;

    (It's ok. I don't need the money.)

    Good, because it's wrong.

    Edit: Bah, Ben beat me by a few seconds...

  • bleh (unregistered)

    [code]private int GetSelected( int selected ) { int constant; constant = -6;

    int firstPower; firstPower = 11; firstPower *= selected;

    int secondPower; secondPower = -6; secondPower *= selected; secondPower *= selected;

    int thirdPower; thirdPower = 1; thirdPower *= selected; thirdPower *= selected; thirdPower *= selected;

    int sum = 0; sum += thirdPower; sum += secondPower; sum += firstPower; sum += constant;

    if (sum == 0) { return selected; }

    sum -= sum;

    return sum; }

  • (cs) in reply to bleh
    bleh:
    private int GetSelected( int selected )
    {
       int constant;
       constant = -6;
    

    int firstPower; firstPower = 11; firstPower *= selected;

    int secondPower; secondPower = -6; secondPower *= selected; secondPower *= selected;

    int thirdPower; thirdPower = 1; thirdPower *= selected; thirdPower *= selected; thirdPower *= selected;

    int sum = 0; sum += thirdPower; sum += secondPower; sum += firstPower; sum += constant;

    if (sum == 0) { return selected; }

    sum -= sum;

    return sum; }

    Wow, very nice... I like it. Clever.

  • Stephen Touset (unregistered) in reply to Bryan
    Bryan:
    private int GetMessage( int selected ) { return ((selected < 0 || selected > 3) ? 0 : selected); }

    1 liner. Not sure if it gets much better than this.

    Use Ruby.

    def get_message(selected) (1..3).member? selected ? selected : 0 end

  • Saffith (unregistered)

    Another Ruby version.

    def GetMessage(selected)
      classDef=<<-END_OF_CLASS_DEF
      class GetMessageClass
        def GetMessageMethod(index)
          if(index<0 or index>3)
            return 0
          else
            return index
          end
        end
      end
      END_OF_CLASS_DEF
      
      eval(classDef)
      gmc=GetMessageClass.new
      mthd=gmc.method("GetMessageMethod")
      return mthd.call(selected)
    end
  • Stephen Touset (unregistered) in reply to Bryan
    Bryan:
    private int GetMessage( int selected ) { return ((selected < 0 || selected > 3) ? 0 : selected); }

    1 liner. Not sure if it gets much better than this.

    Use Ruby.

    def get_message(selected) (1..3).member? selected ? selected : 0 end

  • Adnan (unregistered)

    You can write that in just one line:

    private int GetMessage( int selected ) { return selected; }

  • Hanno (unregistered) in reply to barfing

    The Incompetant, of cause (Refer to the Contractors Note)

  • Hanno (unregistered) in reply to barfing
    barfing:
    anon:
    can't be real

    bwahahaha... I'd agree man, who would tarnish their image with such a gimmick?

    ... I meant to quote this with my previous post.

  • hipsurgery at gee male daht calm (unregistered)

    I'm going to port this over to PHP. Every good code monkey knows that this function would be easier to read if it was OOP...

    <?php require_once('class.message_handler.php'); class Message extends Message_Handler { private $_xLoopStartPointVarInt; private $_errFlagOnIntInitFromFunction; private $_loopValidCounterNoErrReturn; private $_tempValidTestVarInt; private $_tempVarCheckValidNegativeInt private $_tempValidTestVarInt; private $_finalCheckVarValInvalid; public function GetMessage( switchWhichNumToBeReturnedFromThisFunction ) { if ((switchWhichNumToBeReturnedFromThisFunction >=5) || (switchWhichNumToBeReturnedFromThisFunction < 0) || (!is_numeric(switchWhichNumToBeReturnedFromThisFunction)) { $this -> _errFlagOnIntInitFromFunction = true; } else { // verify that the number is valid $this -> _xLoopStartPointVarInt = 0; $this -> _loopValidCounterNoErrReturn = 0; for ($x = this -> _xLoopStartPointVarInt; x<=5; x++) { $this -> _loopValidCounterNoErrReturn = $this -> _loopValidCounterNoErrReturn +1; } if ($this -> _loopValidCounterNoErrReturn >=5) { $this -> _tempValidTestVarInt = false; } $this -> _xLoopStartPointVarInt = 0; for ($x = this -> _xLoopStartPointVarInt; x<=0; x--) { $this -> _tempVarCheckValidNegativeInt++; } if ($this -> _tempVarCheckValidNegativeInt >0) { $this -> _tempVarCheckValidNegativeInt = false; } if (((((!$this -> _tempValidTestVarInt)) || ((!$this -> _tempVarCheckValidNegativeInt))))) { // flag as invald for debugging $this -> _finalCheckVarValInvalid = true; } else { return (((switchWhichNumToBeReturnedFromThisFunction)*2)-1); } } }
  • (cs) in reply to Adnan

    Okay, I decided to do a count of how many people wrote a buggy version of this function. Here are my counts:

    50 -- The number of correct solutions. I didn't count unique solutions or even unique submitters; I just went through and looked at all the posts that had solutions in them that weren't talking about other people's.

    35 -- The number of solutions that I don't know if they work. These usually involved either more thinking than I wanted to put in at midnight (often a lot of bit twiddling) or were in languages that I didn't know and didn't feel like trying to figure out. (Some of the 50 above were also unknown, but I could get a good enough sense.)

    4 -- The number of solutions that are correct except for some trivial mistake. For instance, one post uses = instead of ==. (Or otherwise screws up to make getMessage(0) undefined.)

    7 -- The approximate number that invoke technically undefined behavior in C, even if it's pretty well known what it'll do. For instance, underflowing an integer or casting signed to unsigned. (A couple of the correct solutions should probably be in here.)

    12 -- The number of solutions that are correct only for the numbers 0-3, or some other set. (For instance, there was one correct for all numbers except -3 to -1, which were mapped to their absolute values.)

    2 -- The number of solutions that are correct for positive numbers, but not for negative numbers. (There might be an undefined one here too.)

    8 -- The number of solutions that are otherwise wrong. I think this means that it maps 0-3 to the wrong values, but I don't remember all the instances and can't guarantee I was consistent. (For instance, one maps 0->4.)

    In other words, if you count the undefined behavior ones as wrong and the almost correct ones as correct, 29 out of 83 people -- 35% of answers that I graded implement the function wrong. Even if you assume that all the ungraded answers are correct, that's still 29 of 118 or 25% of answers are wrong.

    There's your WTF.

  • hpeg (unregistered) in reply to EvanED
    EvanED:
    Okay, I decided to do a count of how many people wrote a buggy version of this function. Here are my counts:

    50 -- The number of correct solutions. I didn't count unique solutions or even unique submitters; I just went through and looked at all the posts that had solutions in them that weren't talking about other people's.

    35 -- The number of solutions that I don't know if they work. These usually involved either more thinking than I wanted to put in at midnight (often a lot of bit twiddling) or were in languages that I didn't know and didn't feel like trying to figure out. (Some of the 50 above were also unknown, but I could get a good enough sense.)

    4 -- The number of solutions that are correct except for some trivial mistake. For instance, one post uses = instead of ==. (Or otherwise screws up to make getMessage(0) undefined.)

    7 -- The approximate number that invoke technically undefined behavior in C, even if it's pretty well known what it'll do. For instance, underflowing an integer or casting signed to unsigned. (A couple of the correct solutions should probably be in here.)

    12 -- The number of solutions that are correct only for the numbers 0-3, or some other set. (For instance, there was one correct for all numbers except -3 to -1, which were mapped to their absolute values.)

    2 -- The number of solutions that are correct for positive numbers, but not for negative numbers. (There might be an undefined one here too.)

    8 -- The number of solutions that are otherwise wrong. I think this means that it maps 0-3 to the wrong values, but I don't remember all the instances and can't guarantee I was consistent. (For instance, one maps 0->4.)

    In other words, if you count the undefined behavior ones as wrong and the almost correct ones as correct, 29 out of 83 people -- 35% of answers that I graded implement the function wrong. Even if you assume that all the ungraded answers are correct, that's still 29 of 118 or 25% of answers are wrong.

    There's your WTF.

    Bollocks. That's what proper specs, unit tests, and software testers are for.

    private int getMessage(int selected) { return Math.random()%4; }
  • Faxmachinen (unregistered)
    # cashmachine.py
    
    output = 'private int GetMessage( int selected )\n{\n\
        \tint result = 0;\n\
        \tswitch(selected)\n\t{\n'
    case_head = '\t\tcase '
    case_body = ':\n\t\t\tresult = '
    case_tail = ';\n\t\t\tbreak;\n'
    
    i = int_min
    while (i <= int_max):
        if i < 0 or i > 3:
            output += case_head + str(i) + case_body + '0' + case_tail
        else:
            output += case_head + str(i) + case_body + str(i) + case_tail
        i += 1
    
    output += '\t}\n\treturn result;\n}\n'
    
    ofile = file( 'GetMessage.c', 'w+' )
    ofile.write( output )
    ofile.close()
  • Nefrubyr (unregistered) in reply to Rich
    Rich:
    However, you might want to consider that abs() might be considered as a conditional. True, you could do sqrt(x**2) but sqrt is pretty conditional itself.
    A couple of years ago I was figuring out how to do various operations with bit-twiddling on PPC. Here's how to calculate abs(r3):
    srawi r4,r3,31
    add r3,r3,r4
    xor r3,r3,r4

    I don't know how easy it is to translate to x86. It works because Shift Right Arithmetic Word Immediate copies the sign bit of r3 into every bit of r4, then the other two instructions calculate the two's complement if r3 is negative or do nothing otherwise.

  • Harry (unregistered)

    Very simple ..

    private int GetMessage( int selected ) { return selected; }

    [email protected]

  • Harry (unregistered)

    I do not why you make this function as Case and Index is same case 0: index = 0; break;

          case 1:
              index = 1;
              break;
    
          case 2:
              index = 2;
              break;
    
          case 3:
              index = 3;
              break;
    

    So we you change this function to following code, it will return same result.

    private int GetMessage( int selected ) { return index; }

    Harry [email protected]

  • Zepi (unregistered)

    This really calls for a Duff's Device:

    private int GetMessage( int selected ) { int index=0; int n=(selected+2)/3; if (n<2) ....{ ....index-=3; ....switch (selected%3) ........{ ........case 0: do { index++; ........case 2: ...... index++; ........case 1: ...... index++; ........................} while (--n>0); ........} ....} return index; }

    (please ignore those dots, they are just for indentation)

  • (cs) in reply to acne
    acne:
    Benanov:
    acne:
    Hint : max(a,b) = (a + b + abs(a - b)) /2 and min(a,b) = (a + b - abs(a - b)) / 2

    I have never seen that before, but that is a beautiful piece of mathematics. I have never thought about it before, but it makes sense.

    What's the bigger of two numbers? Find the midpoint between the two numbers, and then add half the distance.

    Subtracting half the distance yields the minimum.

    Kudos to you for sharing that with me!

    You're welcome!

    I saw such constructs in algorithm class. My teacher was quite fond of 'alternative' ways of doing things.

    Another one: how do you swap the values of 2 int variables without using a third variable?

    a = a + b
    b = a - b
    a = a - b

    Sweet. How elegant. Any more of this ?

  • (cs) in reply to Guything McThingGuy
    Guything McThingGuy:
    anon:
    can't be real

    Then this seems the perfect time to bring out the example I found in some billing software:

    if($days == 1) {$time_period = $time_period + 1;}
    if($days == 2) {$time_period = $time_period + 2;}
    if($days == 3) {$time_period = $time_period + 3;}
    if($days == 4) {$time_period = $time_period + 4;}
    if($days == 5) {$time_period = $time_period + 5;}
    if($days == 6) {$time_period = $time_period + 6;}
    if($days == 7) {$time_period = $time_period + 7;}
    if($days == 14) {$time_period = $time_period + 14;}
    if($days == 28) {$time_period = $time_period + 28;}
    

    This was to process a list prompt from a web page. 1 day, 2 days, ..., 1 week, 2 weeks.

    And the code was copy-pasted such that in total I removed about 500 lines just by refactoring this one structure.

    The whole thing had so much copy-paste reuse that it probably could have been reduced to a quarter of its size just by refactoring the redundant code. I stopped at half its size and quit.

    Why did you quit leaving the job refactoring half done ? IMHO, evil like this needs eradicated completely.

  • Hasan Maqbool (unregistered)

    As far as refactoring is concerned, there is not need to write this function. One can use int Selected as it is where he/she wants int index to be.

    Anyhow

    private int GetMessage(int selected) { return (selected>=0 || selected<=3?selected:0)

    }

  • LanguageCollector (unregistered)

    I think we're missing a few languages here; I'll add two of them.

    PostScript:

    %!PS
    

    /GetMessage { dup 0 lt { pop 0 }{ dup 3 gt { pop 0 } if } ifelse } bind def

    % Unit test, as specified by triso /Helvetica findfont 14 scalefont setfont /y 600 def /tos { 8 string cvs } def /p { 50 y moveto /y y 20 sub def show } def

    /s1 (GetMessage() def /s2 () == ) def

    /test { s1 p dup tos show s2 show GetMessage tos show } def

    /numbers [0 1 2 3 4 10000 -1 -5 -10000] def

    numbers { test } forall

    showpage

    F77:

          PROGRAM MAIN
    
      INTEGER I,J
      INTEGER TESTDT(9)
      DATA TESTDT /0, 1, 2, 3, 4, 10000, -1, -5, -10000/
    

    5 FORMAT(A11,I7,A6,I4)

    C TEST THE FUNCTION DO 10 I=1,9 CALL GETMSG(TESTDT(I),J) WRITE(*,5)'GETMSG(',TESTDT(I),') == ',J 10 CONTINUE STOP END

      SUBROUTINE GETMSG(SEL,RES)
      INTEGER SEL,RES
      IF((SEL.LT.0).OR.(SEL.GT.3))THEN
         RES=0
         RETURN
      END IF
      RES=SEL
      END</pre></div></BLOCKQUOTE>
    
  • (cs)

    How you might do it with switch:

    private int GetMessage( int selected )
    {
        switch( selected )
        {
          case 0: 
          case 1: 
          case 2:
          case 3:
            return selected;
    
          default:
            return 0;
        }
    }
    

    For those who don't like returning from the middle of a function you could start with index=0 and skip the default altogether with "index=selected" for the first 3 cases.

  • BruteForce (unregistered) in reply to Ibn al-Hazardous
    Ibn al-Hazardous:
    too_many_usernames:
    acne:
    Hint : max(a,b) = (a + b + abs(a - b)) /2 and min(a,b) = (a + b - abs(a - b)) / 2
    Do you know how long it's been that I've wanted a deterministic (i.e., not relying on conditionals) representation of min/max?

    How sad it is that this is the first time that I've ever seen this representation (after at least 17 years of mathematics and around 6 of computer science)!

    This makes me even more angry at my teacher that told me the answer to "how do I compute sqrt(x) by hand?" was "punch the sqrt key on your calculator."

    Not sure if that's a plea, but I'll bite: http://blueturtle.nu/filip/square-root-HOWTO.html (It's a bit too long for inlining in the forum.)

    There is an interresting sqrt in the Quake engine. With an even more interresting comment on it (Dunno if it was cleaned, but it was in the leaked version). Cant remember it now, but I seem to remember some fancy bitshifting and stuff. And the comment were: //wtf?!

  • Omg (unregistered)

    the real wtf is amount of noobs in here, who can't write it right. no wonder world is full of wtfs when half of readers of TDWTF.com are wtfers

  • robfero (unregistered)

    What about an OO pattern-wise implementation?

    That's it...

    public class GetMessageImpl { public int getMessage(int selected) { CommandInterface command=CmdFactory.getCommand(selected); return command.getMessage(); } }

    public class CmdFactory { public static CommandInterface getCommand(int i) { try { return Class.forName("Command"+i).newInstance(); } catch (Exception e) { return new CommandDefault(); } } }

    public interface CommandInterface { public int getMessage(); }

    public class CommandDefault implements CommandInterface { public int getMessage() { return 0; } }

    public class Command0 implements CommandInterface { public int getMessage() { return 0; } }

    public class Command1 implements CommandInterface { public int getMessage() { return 1; } }

    public class Command2 implements CommandInterface { public int getMessage() { return 2; } }

    public class Command3 implements CommandInterface { public int getMessage() { return 3; } }

    I'm thinking about an EJB solution.....

  • Oliver (unregistered)

    Hurrah

    int getMessage(int c){ return c*!(1-!(c>>(!!('<'-'>')["<<"]<<!!('>'>"<]"[!'>']))))&3; }

  • (cs)
    Omg:
    Omg:
    the real wtf is amount of noobs in here, who can't write it right. no wonder world is full of wtfs when half of readers of TDWTF.com are wtfers

    especially [email protected] who even put his email to be contacted by headhunter for his brillant code

    is Omg Object Management Group (CORBA etc) or Oh My Gosh!

    We don't know the context here, however I would say that a function called GetMessage should get a message, not a number between 0 and 3.

  • Oliver (unregistered) in reply to Oliver

    dammit, i can make it more efficient:

    int getMessage(int c){ 
       return c*!(1-!(c>>(!!('<'-'>')["<<"]<<!!('>'>"<]"[!'>'])))); 
    }
    

    I have now saved that nasty & :D

  • (cs) in reply to too_many_usernames
    too_many_usernames:
    acne:
    Hint : max(a,b) = (a + b + abs(a - b)) /2 and min(a,b) = (a + b - abs(a - b)) / 2
    Do you know how long it's been that I've wanted a deterministic (i.e., not relying on conditionals) representation of min/max?

    How sad it is that this is the first time that I've ever seen this representation (after at least 17 years of mathematics and around 6 of computer science)!

    This makes me even more angry at my teacher that told me the answer to "how do I compute sqrt(x) by hand?" was "punch the sqrt key on your calculator."

    What's deterministic about abs? It has to check the sign. You need to use sqrt((a-b)(a-b)) instead.

  • weaver (unregistered) in reply to Aerendel

    The way Im reading it selected is a string, seeing as the function returns an int I can assume that the user simply didnt want to/know how to cast selected to an int.

    could probably be summed up as:

    int index = int.parse(selected); if ((int < 1) || (int > 3)) { index = 0; } return index;

    I know that the if could be shortened, but this is "good enough" (TM)

  • (cs) in reply to John Doe

    int GetMessage(int value) { int index = -(valuevaluevalue - 6valuevalue + 5*value - 6)/6;

    return (index == value) ? index : 0; }

  • Faxmachinen (unregistered) in reply to LanguageCollector
    LanguageCollector:
    I think we're missing a few languages here;
    AT&T ASM:
    	movl %%eax,%%ebx	; Make copy
    	shrl $2,%%ebx		; Shift out two bits (sets zero flag)
    	movl %%eax,%%ebx	; Copy again
    	jz skip			; If zero flag, skip next step
    	movl $0,%%ebx		; Set to 0
    skip:	nop
  • linepro (unregistered) in reply to Stephen Touset

    (selected &= 3);

    // Any better ?

  • SunriseSolutions (unregistered)

    Yes, but look how easy to read it is, and how clearly you can see that it is a useless function that just assigns the value of the "selected" int indicating the message to the variable "index". The whole function can be replaced by one line wherever the function is called:

    index = selected;

    Where the contractor can really make the big bucks, and be applauded, is in in the accompanying 2 pages of documentation that describe the design decision to use the standard "index" variable across all programs. For every line of code there should be at least 5 lines of documentation, right? :-)

  • PC Paul (unregistered) in reply to cklam
    cklam:
    acne:

    Another one: how do you swap the values of 2 int variables without using a third variable?

    a = a + b
    b = a - b
    a = a - b

    Sweet. How elegant. Any more of this ?

    It's nice. Until you start handling big numbers...

  • n00b Programmer (unregistered)

    //the program

    main { } //I'm great!

  • Omg like oh my Goddess (unregistered) in reply to linepro
    linepro:
    (selected &= 3);

    // Any better ?

    yeah, what about something not buggy noob?

    captcha:muhahaha, how fitting

  • biff (unregistered) in reply to EvanED
    EvanED:
    biff:
    index = selected;

    (It's ok. I don't need the money.)

    Good, because it's wrong.

    Edit: Bah, Ben beat me by a few seconds...

    It also won't compile. ;)

  • Martijn (unregistered)

    return ((selected & 0xFFFFFFFC)? 0 : selected);

    or, without the branch:

    return selected * (((selected & 0xFFFFFFFC) / (selected & 0xFFFFFFFC)) ^ 0x1);

    I have no doubt it can be done faster :)

  • (cs) in reply to Alchymist
    Alchymist:
    What's deterministic about abs? It has to check the sign. You need to use sqrt((a-b)(a-b)) instead.

    From Wikipedia: "In computer science, a deterministic algorithm is an algorithm which, in informal terms, behaves predictably. Given a particular input, it will always produce the same correct output, and the underlying machine will always pass through the same sequence of states"

    abs(4) always equals 4. abs(-3) always equals 3. Having branches DOES NOT EQUAL nondeterministic. The following is deterministic:

    int abs(int x) {
      if(x<0) return -x;
      return x;
    }
    PC Paul:
    cklam:
    acne:

    Another one: how do you swap the values of 2 int variables without using a third variable?

    a = a + b
    b = a - b
    a = a - b

    Sweet. How elegant. Any more of this ?

    It's nice. Until you start handling big numbers...

    Then you can switch to the xor version, also posted above: a = a^b; b = a^b; a = a^b;

    Also, I never worked this problem through to completion, but I think on 2's complement architectures at least the over and underflow works such that the arithmetic version will still work. Could be wrong about that though.

  • Bill (unregistered) in reply to EvanED
    EvanED:
    Okay, I decided to do a count of how many people wrote a buggy version of this function. Here are my counts:

    ...

    In other words, if you count the undefined behavior ones as wrong and the almost correct ones as correct, 29 out of 83 people -- 35% of answers that I graded implement the function wrong. Even if you assume that all the ungraded answers are correct, that's still 29 of 118 or 25% of answers are wrong.

    There's your WTF.

    Very well put. I've only been reading this site for a week or two, but I'm amazed at the poor S/N ratio on here.

    I've been inheriting other peoples' code off and on for two decades now, and the original code smells like either: (a) a stub itended to get other processing code in the 1-3 branches, or (b) a routine that got reworked over time to no longer have meaning, yet has remained for purely org reasons like fear of unintended side-effects from cleaning it up.

    My money is on (a). The rest of this thread is an exercise in hand warmers.

  • Faxmachinen (unregistered) in reply to acne
    acne:
    Another one: how do you swap the values of 2 int variables without using a third variable?
    asm("xchgl %%eax,%%ebx" : "=a"(a), "=b"(b) : "a"(a), "b"(b) :);

    The advantage over swap(a, b); is that a and b don't have to be of the same type. Although, in the wrong hands that would probably be a disadvantage.

  • Eric (unregistered)

    You're all missing the real purpose of the code.

    Sure, for now it looks silly, but what you've missed is that it provides an excellent customization opportunity.

    The code that says:

    case 1: index = 1; break;

    will at some point be replaced with:

    case 1: index = 1; if ((lastIndex == 12) || (employeeCount == 3)) index = 2; // code was wrong in these cases

  • Guything McThingGuy (unregistered) in reply to cklam
    cklam:
    Guything McThingGuy:
    anon:
    can't be real

    Then this seems the perfect time to bring out the example I found in some billing software:

    if($days == 1) {$time_period = $time_period + 1;}
    if($days == 2) {$time_period = $time_period + 2;}
    if($days == 3) {$time_period = $time_period + 3;}
    if($days == 4) {$time_period = $time_period + 4;}
    if($days == 5) {$time_period = $time_period + 5;}
    if($days == 6) {$time_period = $time_period + 6;}
    if($days == 7) {$time_period = $time_period + 7;}
    if($days == 14) {$time_period = $time_period + 14;}
    if($days == 28) {$time_period = $time_period + 28;}
    

    This was to process a list prompt from a web page. 1 day, 2 days, ..., 1 week, 2 weeks.

    And the code was copy-pasted such that in total I removed about 500 lines just by refactoring this one structure.

    The whole thing had so much copy-paste reuse that it probably could have been reduced to a quarter of its size just by refactoring the redundant code. I stopped at half its size and quit.

    Why did you quit leaving the job refactoring half done ? IMHO, evil like this needs eradicated completely.

    Because I was being paid half-a-pittance, and after refactoring, I still would have been left with refactored crap.

  • A (unregistered)

    private int GetMessage( int selected ) { return (selected & 3) == selected ? selected : 0; }

  • Bill (unregistered) in reply to SunriseSolutions
    SunriseSolutions:
    Yes, but look how easy to read it is, and how clearly you can see that it is a useless function that just assigns the value of the "selected" int indicating the message to the variable "index". The whole function can be replaced by one line wherever the function is called:

    index = selected;

    Where the contractor can really make the big bucks, and be applauded, is in in the accompanying 2 pages of documentation that describe the design decision to use the standard "index" variable across all programs. For every line of code there should be at least 5 lines of documentation, right? :-)

    Amazing that after 5 (FIVE) pages of commentary, people are still missing the basic logic of the initial post and posting flawed code. I have to agree with others here: the real WTF is all the folks posting on here that look down their noses at some poor, out-of-context example and then return to their jobs where they most likely write code just as flawed as what they post here.

  • Mike5 (unregistered) in reply to LanguageCollector
    LanguageCollector:
    I think we're missing a few languages here; I'll add two of them.

    PostScript:

    %!PS
    

    /GetMessage { dup 0 lt { pop 0 }{ dup 3 gt { pop 0 } if } ifelse } bind def ...

    F77:

          PROGRAM MAIN
    
      INTEGER I,J
      INTEGER TESTDT(9)
    

    ...

    Pascal:

    program DoTheFunStuff(Output);
    const LoBound = 0;
          HiBound = 3;
    var  i : integer;
    function GetMessage( n : integer ) : integer;
    begin
      if ( n < LoBound ) or ( n > HiBound ) then
        GetMessage := 0
      else
        GetMessage := n;
    end;
    begin
      for i := -5 to 7 do
        WriteLn( 'Input ', i, ' - output ', GetMessage( i ) );
    end.
    

    Hope I still remember it correctly.

  • me (unregistered) in reply to Maks Verver

    @Maks Verver

    I'll go with: int GetMessage(int s)

    {

    return s&~3 ? 0 : s;
    

    } Can this be improved? (I doubt it!)

    might be faster (in some cases, but i'm not sure):

    int GetMessage(int s){ return ( ((unsigned int)s < 4) ? s : 0); }

  • Anonymous (unregistered)

    Another Pascal solution, and rather close to the original code:

    function getMessage(Selected: integer): integer;
    begin
      case Selected of
        0-4:  Result:=Selected;
        else: Result:=0;
      end;
    end;

Leave a comment on “Paid by the Line”

Log In or post as a guest

Replying to comment #:

« Return to Article