• Javier Resendiz (unregistered) in reply to Aaron

    Man!

    You are my new Coder Hero.

  • slinkp (unregistered) in reply to tuffy

    Ah, that's cute, I'd forgotten about constructing dicts from lists of tuples. Meanwhile I'd thought of a few simple (but pointless of course) solutions:

    def using_bools(i): # this is obvious and probably best return (0 < i < 4) and i or 0

    def using_max(i): if i > 3: i = 0 return max(i, 0)

    def using_range(i): if i not in range(4): i = 0 return i

    def using_dict(i): map = {1:1, 2:2, 3:3} return map.get(i, 0)

  • AI (unregistered)

    public int getMessage(int selected){ ..return (selected <= 3) * selected; }

  • Henrik Schmidt (unregistered) in reply to acne

    [quote user='acne']Another one: how do you swap the values of 2 int variables without using a third variable?[/quote]

    Fairly simple in Ruby:

    a,b = b,a

  • Milkshake (unregistered)

    Am I the only person who read the method name? Chances are, this was used for executing some additional code or dumping some log messages and the contents were later removed. I'm as cynical as the next person, but give me break.

    Captcha: stinky (like this wtf)

  • PseudoNoise (unregistered)

    1 line:

    private int GetMessage( int selected ) { int index = 0; switch( selected ) { case 0: index = 0; break; case 1: index = 1; break; case 2: index = 2; break; case 3: index = 3; break; } return index; }
  • Maks Verver (unregistered) in reply to <3lylegs
    <3lylegs:
    Maks Verver:
    s&~3 ? 0 : s
    Can this be improved? (I doubt it!)
    Because you ask, yes it can. Removing the conditional element for example.
    !(s&~3)*s
    Although Java will probably throw a tantrum because of the int->bool->int casts. But I assume java can be coerced.
    I actually considered that, but rejected it both because it's not valid Java code, and it's actually one (non-space) character longer!
  • Rich (unregistered) in reply to too_many_usernames
    too_many_usernames:
    Do you know how long it's been that I've wanted a deterministic (i.e., not relying on conditionals) representation of min/max?
    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.
    too_many_usernames:

    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."

    Do ln(x) on your calculator, divide by 2 by hand then enter e**(y) on your calculator. sqrt by hand :D

    Rich

  • slinkp (unregistered)

    Oh, and somebody asked about using XML. Well hey, XSLT can do anything, right? :) Untested but something like this might work:

    xsl:choose <xsl:when test="$selected = 1"> xsl:text1</xsl:text"> </xsl:when> <xsl:when test="$selected = 2"> xsl:text2</xsl:text"> </xsl:when> <xsl:when test="$selected = 3"> xsl:text3</xsl:text"> </xsl:when> xsl:otherwise xsl:text0</xsl:text> </xsl:otherwise> </xsl:choose>

  • Dan (unregistered)

    I'm surprised no-one's thought about coding this in INTERCAL yet. Or befunge.

  • Peter Antoine (unregistered) in reply to slinkp

    because someone stupidly mentioned hardware: (VHDL - uncompiled, prob. wont work, for m68k - IANAHD)

    library.ieee; use ieee.std_logic_1164.all;

    entity GetMessage is port map ( enable : in std_logic; --- lets the address decoding be done elsewhere (active high) rw : in std_logic; as : in std_logic; lds : in std_logic; reset : in std_logic; din : in std_logic_vector(15 downto 0);

    			dout	: out std_logic_vector(15 downto 0);
    );
    

    end entity GetMessage;

    architecture rtl of GetMessage is

    signal local_data is std_logic_vector(15 downto 0);
    signal write_sel is std_logic;
    signal read_sel is std_logic;
    

    begin

    write_sel <= not rw and not as and not lds and not clock and enable;
    read_sel  <= rw and not as and not lds and enable;
    
    process (reset,write_sel)
    begin
    	if (reset = '0')
    	then
    		local_data <= (others => '0')
    	
    	elsif (selected'event and selected = '1')
    	then
    		if (din(15 downto 3) = "000000000000")
    		then
    			case din(2 downto 0) is
    				when "001"  => local_data(2 downto 0) <= "001"; 
    				when "010"  => local_data(2 downto 0) <= "010"; 
    				when "011"  => local_data(2 downto 0) <= "011"; 
    				when others => local_data(2 downto 0) <= "000";
    			end case;
    		end if;	
    	end if;
    end process;
    
    dout <= local_data when read_sel else (others => 'Z');
    

    end architecture rtl;

  • John Doe (unregistered)

    I was also amazed that there is no XML based solution. Anyways, here it is.

    File messageIds.xml: <MessageIds> <MessageId key="0">0</MessageId> <MessageId key="1">1</MessageId> <MessageId key="2">2</MessageId> <MessageId key="3">3</MessageId> <DefaultMessageId>0</DefaultMessageId> </MessageIds>

    Now the code: int index = 0; XmlDocument oDoc = new XmlDocument(); oDoc.Load("messageIds.xml"); XmlNode oNode = oDoc.selectSingleNode("MessageIds/MessageId[@key=" + selected.ToString() + "]"); if(oNode == null) oNode = oDoc.selectSingleNode("MessageIds/DefaultMessageId"); if(oNode != null) index = Convert.ToInt32(oNode.FirstChild.Value);

  • John Doe (unregistered)

    A variant of the switch statement:

    private int GetMessage( int selected ) { int index = 0;

    // Get the Message switch( selected ) { case 3: index++; case 2: index++; case 1: index++; } return index; }

  • Mark Christian (unregistered)

    I think I win:

    int GetMessage(int selected)
    {
    	return (selected < 0 || selected > 3) ? 0 : 1 + GetMessage(--selected);
    }
    
  • Anon (unregistered)

    Instead of rewriting this function shouldn't we just choose not to use it?

    // BAD x = GetMessage(selected);

    // NOT SO MUCH variable = selected;

  • Ibn al-Hazardous (unregistered) 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."

    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.)

  • mathew (unregistered)

    I think a Perl solution is needed.

    sub GetMessage {('#'x shift)=~/^(#{1,3})$/,length $1;}

  • Maks Verver (unregistered) in reply to too_many_usernames
    too_many_usernames:
    Do you know how long it's been that I've wanted a deterministic (i.e., not relying on conditionals) representation of min/max?
    That's a very strange definition of 'deterministic' you use, but even for your definition you've only moved the conditional code to the implementation of abs.

    I don't think there is a way to write a completely general 'conditional-free' version of abs, but for a fixed-width register, you could do something like (in C):

    #include <limits.h>
    int my_abs(int r)
    {
    return (r^r>>sizeof(int)*CHAR_BIT-1) +
    (1&r>>sizeof(int)*CHAR_BIT-1);
    }

    This code only works for 2's complement representation of signed integers (the most common); for 1's complement and signed magnitude representations it's actually easier (and it avoids the case of r == INT_MIN, for which there is no answer).

    The idea is that if the number given is negative, it must be converted to a positive one. This is done by inverting all bits and adding one. Now how do we make sure this only happens for negative values? Why, by using the sign bit as a variable ofcourse! (When the sign bit is 0, the expression evaluates to r^0 + 0 which is just r, but when the sign bit is 1, the expression is r^0xff..ff + 1.)

    A nice exercise is to the determine the operator precedence in this code, without looking in the manual ;) Also, remember that >> is an arithmetic shift (i.e. it does sign extension).

  • Guything McThingGuy (unregistered)
    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.

  • Rich (unregistered) in reply to Maks Verver
    Maks Verver:
    The idea is that if the number given is negative, it must be converted to a positive one. This is done by inverting all bits and adding one. Now how do we make sure this only happens for negative values? Why, by using the sign bit as a variable ofcourse! (When the sign bit is 0, the expression evaluates to r^0 + 0 which is just r, but when the sign bit is 1, the expression is r^0xff..ff + 1.)

    Ah, but you see, you've just pushed the conditional back a little bit further as sizeof(int) and CHAR_BIT are conditional on the processor used.

    Possibly, you might be able to argue that a roll-left (places the MSB in the LSB position) command would qualify as unconditional as it is a simple mechanical operation of the processor.

    Rich

  • Was Anders (unregistered)

    from math import pi, ceil

    def GetMessage(selected): return int((ceil(min(pi, selected)) % 4)*(selected>0))

  • Anonymous (unregistered) in reply to tuffy
    tuffy:
    I think the proper Python version should be:

    def GetMessage(selected): return dict([(x,x) for x in range(4)]).get(selected,0)

    That's a perfect opportunity to use Python 2.5's new conditional expressions!

    def GetMessage(value):
    	return value if value in [1, 2, 3] else 0
  • Anonymous (unregistered)

    So many people here mised the obvious... here is your "shortest function":

    Yes, that's right, do away with the function completely and in-line it with whatever code it calls. It's a simple input equals output with invariant bounds constraints, it can be trivially done on one line (as shown elsewhere in this thread) so inlining it is entirely reasonable.

    The real WTF here is why something like that requires "a complete rewrite" of the entire system - it's a pretty simple refactor as everyone here has shown. I think perhaps Frank's company are trying to milk this contract for all it is worth?

  • J the anon (unregistered) in reply to bzr
    bzr:
    Paul J:
    OK, more bit-twiddling an added evilness:

    int getmessage (int c) { return (!(c&~3))["(c&3)"]&c&3; }

    That is the most evil thing I have ever seen... it does compile and work though ;-)

    I bow my head in awe!

  • EhMon (unregistered) in reply to hpeg

    Then you've got to pour through the code and change all calls to GetMessage() and change them to a call to Math.min.

    No, thanks.

  • (cs)
    -- the setup
    CREATE TABLE indexvals 
    (index_num NUMBER(1)
    ,spell_out VARCHAR2(5));
    
    
    CREATE OR REPLACE PROCEDURE GETMESSAGE
       (p_selected NUMBER) 
    AS
       v_min_idx    NUMBER(1) := 1;
       v_max_idx	NUMBER(1) := 3;
       v_spell_out	VARCHAR2(5);
       v_count	NUMBER(1);
       v_new_idx 	NUMBER(1);
       v_insert     NUMBER(1);
    
    BEGIN
       FOR v_count IN v_min_idx..v_max_idx LOOP
          v_insert := 1;
          IF v_count = 1 THEN
             v_spell_out := 'one';
          ELSIF v_count = 2 THEN
             v_spell_out := 'two';
          ELSE
             v_spell_out := 'three';
          END IF;
          WHILE v_insert < v_count+1 LOOP
             insert into indexvals values (v_count,v_spell_out);
             v_insert := v_insert + 1;
          END LOOP;
          commit;
       END LOOP;
       -- watch closely
       update indexvals
       set spell_out = 'WTF'
       where index_num = p_selected;
       v_new_idx := SQL%ROWCOUNT;
       commit;
       dbms_output.put_line(v_new_idx);
    END;
    /
    
    SQL> exec getmessage(2);
    2
    
    PL/SQL Procedure successfully completed.
    
    SQL>
    
    
  • Thijs (unregistered) in reply to Otterdam
    Otterdam:
    (I'm not a Java/C#er here, but it ought to make sense to them anyway) [#include <algorithm> and <list> is implied, of course]
          
          // Create list of allowed index values
          int newindex1 = 0;
          indexes.push_back(newindex1);
          int newindex2 = 1;
          indexes.push_back(newindex2);
          int newindex3 = 2;
          indexes.push_back(newindex3);
          int newindex4 = 3;
          indexes.push_back(newindex4);
    
          // Ensure list is sorted in ascending order
          // 12/01/2007 changed to built in sort - apparently it is faster than bubble sort ????
          indexes.sort();
    
    

    Not necessarily. Bubble sort is fast for sorted data.

  • grumble (unregistered) in reply to Paul J
    Paul J:
    OK, more bit-twiddling an added evilness:

    int getmessage (int c) { return (!(c&~3))["(c&3)"]&c&3; }

    Bah, that's nothing. Anything can be made opaque with bad perl. This is a actually very neat minimal case I've just made it ugly.

    sub getmessage { ($_[0]=~/^([1-3])$/)?$1:0; }

  • (cs) in reply to Licky Lindsay
    Licky Lindsay:
    static int getMessage(int selected) { try { int[] messages = {0,1,2,3}; return messages[selected]; } catch (ArrayIndexOutOfBoundsException e) { return 0; } }

    That was going to be my solution!

    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?

    "Not relying on conditionals" != "deterministic".

    Why would you want something like that besides just the mathematical elegance? Or is that all?

    (I can almost guarantee the above will be slower than (x>y)?x:y, since how are you going to implement abs? Typically, (x>0)?x:-x. You can also do it with sqrt(x*x), but then how are you going to do sqrt? You need a loop. Hence, conditional. Though I guess Maks Verver gives a branch-free implementation of abs...)

    Anon:
    Instead of rewriting this function shouldn't we just choose not to use it?

    // BAD x = GetMessage(selected);

    // NOT SO MUCH variable = selected;

    You're not preserving semantics.

    Granted, the semantics may not be worth it to preserve, but it's still different.

    Rich:
    Ah, but you see, you've just pushed the conditional back a little bit further as sizeof(int) and CHAR_BIT are conditional on the processor used.

    That's not a conditional though... that's decided at compile time. (And as such it's actually dependent on the compiler rather than the processor, but that's another story.) Using either of these isn't an 'if' in the code, and won't be compiled to anything including a branch instruction unless your compiler is trying to be difficult.

  • Stevan (unregistered) in reply to Kennie Nybo Pontoppidan

    Even simpler in OCaml

    let get_message = function 
         | x when x <= 4 -> x
         | _ -> 0
    
  • jLoyd (unregistered)
    public int getMessage(int selected){
       Integer result = null;
    
       do{
          result = new Integer((int)(Math.random()*100));
       }while(result.intValue() != selected);
    
       return result.intValue();			
    }
    

    Why not????

  • (cs) in reply to EvanED
    EvanED:
    "Not relying on conditionals" != "deterministic".

    Actually I think that this isn't true. If you consider 'conditional' not unreasonably broadly, then no conditionals -> deterministic.

    But "relying on conditionals" != "nondeterministic" is certainly true.

  • (cs)

    To be extra effective:

    private int GetMessage( int selected ) { if IsTrue(selected > 0) return selected; else return 0; }

  • (cs)

    All I seem to be missing is an implementation in brainfuck ;)

    (http://en.wikipedia.org/wiki/Brainfuck)

  • Adam (unregistered)

    private int GetMessage( int selected ) { if (selected < 1 || selected > 3) return 0; return (GetMessage(selected - 1) + 1); }

    How about this?

  • Aaron (unregistered)

    I could probably update my factory code to get the class names from a SQL or XML lookup table. I didn't even think of that, there's definitely an opportunity for increasing the LOC because you'd really need an entire business tier for it to be truly flexible, robust, and thoroughly useless. I can see a typed DataSet, a DAL, and a BLL here, along with perhaps a Stored Procedure or two. I don't really have time to implement it now though, so I'll leave that as an exercise for the reader. ;)

    Licky Lindsay wins the price for most creative, clever, and horribly inefficient implementation with the use of Random().

    To whoever said Abs(x) can't be implemented without a conditional, how about sqrt(x^2)?

    Oh, and to Milkshake who said we didn't read the method name: You're assuming "message" is from a log or something, but since this code was found in a Web Service, it's not a very good assumption. In fact, every single call to a Web Service is a "message" so it's hard to say what's meant here without knowing the context.

    Finally, to John Doe who posted this code:

    A variant of the switch statement:

    private int GetMessage( int selected ) { int index = 0;

    // Get the Message switch( selected ) { case 3: index++; case 2: index++; case 1: index++; } return index; }

    I haven't actually tried, but I don't believe that code will compile in C#, which doesn't allow implicit fall-through. So, better luck next time!

  • Rich (unregistered)

    Wonderful wonderful Perl:

    sub getMessage{(grep{$==$[0]}1..3)[0]||0}

  • ColinA (unregistered)

    I think what amuses me the most is that most of the proposed rewrites don't actually give the same resulting value as the original function.

    One could spot a number of WTF's in that simple fact, particularly considering the audience and the site these solutions are posted on. :)

  • TimeWarped (unregistered)

    I'm ticked to see verbosity coming back into vogue. How 'bout:

    IDENTIFICATION DIVISION. PROGRAM-NAME. GET-MESSAGE.

    DATA DIVISION. WORKING-STORAGE SECTION. 01 WTF-IS-IT USAGE COMPUATIONAL. 88 IN-RANGE VALUES 0 THRU 3.

    LINKAGE SECTION. 01 SELECTED USAGE COMPUTATIONAL. 01 RETURNED USAGE COMPUTATIONAL.

    PROCEDURE DIVISION. GET-MESSAGE. MOVE SELECTED TO WTF-IS-IT. IF IN-RANGE MOVE SELECTED TO RETURNED ELSE MOVE ZERO TO RETURNED. EXIT PROGRAM.

  • (cs)

    Surely, this must be the optimal way:

    template <int i> struct getmessage
    {	static const int value=0; };
    template <> struct getmessage<1>
    {	static const int value=1; };
    template <> struct getmessage<2>
    {	static const int value=2; };
    template <> struct getmessage<3>
    {	static const int value=3; };
    
    extern int GetMessage(int in)
    {
    	if (in == 1)
    		return getmessage<1>::value;
    	else if (in == 2)
    		return getmessage<2>::value;
    	else if (in == 3)
    		return getmessage<3>::value;
    	else
    		return getmessage<42>::value;
    }

    Addendum (2007-01-31 15:18):

    #define BILLION *1000000
    #define MAPALOT (int*)mmap(NULL, 1 BILLION, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
    int *GetMessageBuf[2]={MAPALOT, MAPALOT};
    int GetMessage2(int in)
    {
    	GetMessageBuf[0][1]=1;
    	GetMessageBuf[0][2]=2;
    	GetMessageBuf[0][3]=3;
    	return GetMessageBuf[in&INT_MIN][in];
    }
  • Tetsuo29 (unregistered) in reply to Katalgar

    Your function/method isn't correct. Your function will return 1,2,3 for -1,-2,-3 when in the original, these would have returned 0.

  • A. Y. Use (unregistered)
    private int GetMessage( int selected )
      {
          char *lookup = "1248", *p = 0;
          int i;
          for (i = 1; ++p < selected; i += i);
          p = strrchr(lookup, i + 0x30);
          *(p + 1) = 0;
          return (int)(log((double)atoi(p)) / log(2.0));
      }
    
  • Arne Martin (unregistered)

    Here's how it would look in Argh!:

    lsj0  1  2  3
     2LPq1Pq2Pq3Pq

    The second caracter on the second line is the "input."

  • (cs) in reply to mathew
    mathew:
    I think a Perl solution is needed.

    sub GetMessage {('#'x shift)=~/^(#{1,3})$/,length $1;}

    You call that Perl? This is Perl:
    my $GetMessage = sub{sub{my($l)=@_;$;=q{sub{
                     my($I)=@_;$l->(sub{$I->($I)
                     (@_)})}};eval(qq{$;->($;)})
                     }->(sub{my($l)=@_;sub{$_[0]
                     [0]==$_[0][1]&&$_[0][0]||$_
                     [0][0]&&$l->([$_[0][0]-1,$_
                     [0][1]])}})([+1+2,$_[0]])};
    See, far more readable, maintainable, and comprehensible than your regular expression-based solution could ever be!

    (The above also fulfils a request a page or two back for a recursive solution using the Y combinator.)

  • Maniac-X (unregistered)

    private int GetMessage( int selected ) { int index = 0;

      // Get the Message
      if (selected > 0)
      {
          if (selected > 1)
          {
             if (selected > 2)
             {
                index = 3;
             } else {
                index = 2;
             }
          } else {
             index = 1;
          }
      }
      return index;
    

    }

    or better yet

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

  • Mark Byers (unregistered)

    int getMessage(int t){return t>>2?0:t;}

  • (cs) in reply to Aaron
    Aaron:
    To whoever said Abs(x) can't be implemented without a conditional, how about sqrt(x^2)?

    How do you propose to implement sqrt without a conditional?

    Only way I know how is with a loop or recursion.

    Aaron:
    Finally, to John Doe who posted this code:
    A variant of the switch statement:

    private int GetMessage( int selected ) { int index = 0;

    // Get the Message switch( selected ) { case 3: index++; case 2: index++; case 1: index++; } return index; }

    I haven't actually tried, but I don't believe that code will compile in C#, which doesn't allow implicit fall-through. So, better luck next time!

    It won't compile as written, but it's not hard to change either. You are allowed to goto a case label, so you can do:

    ... case 3: index++; goto case 2; case 2: index++; goto case 1; case 1: index++; ...

    (Untested)

  • edu (unregistered)

    private int GetMessage( int selected ) { int i; for (i = 0; ; i++) { if ( i == selected) return i; } }

  • allo (unregistered)

    This is the result of refactoring.

    before:

    ...
    switch(selected){
    case 0:
    printf("some error");
    break
    ...
    }
    

    now:

    printf(getMessage(selected));
    

    And the one, who has done the refactoring, did not realize, that its now a lot easier

  • kvigor (unregistered)

    Dammit, olsner already beat me to the partial template specialization. Oh well, mine's more obfuscated.

    class onePaula
    {
       int magic() { return 7; }
    };
    
    class twoPaula
    {
       int magic() { return 2; }
    };
    
    class threePaula
    {
       int magic() { return -1; }
    };
    
    template <class T> int magic()
    {
       return 0;
    }
    
    template <> int magic<onePaula>()
    {
        return 3;
    }
    
    template <> int magic<twoPaula>()
    {
        return 1;
    }
    
    template <> int magic<threePaula>()
    {
        return 2;
    }
    
    int getMessage(int i)
    {
        switch(i)
        {
            case 1:
            return magic<twoPaula>();
            case 2:
            return magic<threePaula>();
            case 3:
            return magic<onePaula>();
        }
    
        return magic<void *>();
    }
    

    // long time listener, first time caller

Leave a comment on “Paid by the Line”

Log In or post as a guest

Replying to comment #:

« Return to Article