- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
Man!
You are my new Coder Hero.
Admin
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)
Admin
public int getMessage(int selected){ ..return (selected <= 3) * selected; }
Admin
[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
Admin
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)
Admin
1 line:
Admin
Admin
Do ln(x) on your calculator, divide by 2 by hand then enter e**(y) on your calculator. sqrt by hand :D
Rich
Admin
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>
Admin
I'm surprised no-one's thought about coding this in INTERCAL yet. Or befunge.
Admin
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);
end entity GetMessage;
architecture rtl of GetMessage is
begin
end architecture rtl;
Admin
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);
Admin
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; }
Admin
I think I win:
Admin
Instead of rewriting this function shouldn't we just choose not to use it?
// BAD x = GetMessage(selected);
// NOT SO MUCH variable = selected;
Admin
Admin
I think a Perl solution is needed.
sub GetMessage {('#'x shift)=~/^(#{1,3})$/,length $1;}
Admin
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):
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).
Admin
Then this seems the perfect time to bring out the example I found in some billing software:
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.
Admin
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
Admin
from math import pi, ceil
def GetMessage(selected): return int((ceil(min(pi, selected)) % 4)*(selected>0))
Admin
That's a perfect opportunity to use Python 2.5's new conditional expressions!
Admin
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?
Admin
I bow my head in awe!
Admin
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.
Admin
Admin
Not necessarily. Bubble sort is fast for sorted data.
Admin
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; }
Admin
That was going to be my solution!
"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...)
You're not preserving semantics.
Granted, the semantics may not be worth it to preserve, but it's still different.
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.
Admin
Even simpler in OCaml
Admin
Why not????
Admin
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.
Admin
To be extra effective:
private int GetMessage( int selected ) { if IsTrue(selected > 0) return selected; else return 0; }
Admin
All I seem to be missing is an implementation in brainfuck ;)
(http://en.wikipedia.org/wiki/Brainfuck)
Admin
private int GetMessage( int selected ) { if (selected < 1 || selected > 3) return 0; return (GetMessage(selected - 1) + 1); }
How about this?
Admin
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:
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!Admin
Wonderful wonderful Perl:
sub getMessage{(grep{$==$[0]}1..3)[0]||0}
Admin
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. :)
Admin
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.
Admin
Surely, this must be the optimal way:
Addendum (2007-01-31 15:18):
Admin
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.
Admin
Admin
Here's how it would look in Argh!:
The second caracter on the second line is the "input."
Admin
(The above also fulfils a request a page or two back for a recursive solution using the Y combinator.)
Admin
private int GetMessage( int selected ) { int index = 0;
}
or better yet
private int GetMessage( int selected ) { return selected; }
Admin
int getMessage(int t){return t>>2?0:t;}
Admin
How do you propose to implement sqrt without a conditional?
Only way I know how is with a loop or recursion.
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)
Admin
private int GetMessage( int selected ) { int i; for (i = 0; ; i++) { if ( i == selected) return i; } }
Admin
This is the result of refactoring.
before:
now:
And the one, who has done the refactoring, did not realize, that its now a lot easier
Admin
Dammit, olsner already beat me to the partial template specialization. Oh well, mine's more obfuscated.
// long time listener, first time caller