• JackBauer (unregistered) in reply to Daid

    This may be the first time I'm posting, but " char Buffer[16000];//16K is always enough. " is probably what just made me spit out my drink. Extra WTF++++ points for the solution. And a gold star sticker.

  • Sack Scratcherton (unregistered)

    switch (selected) { case 0: return selected; break;

    case 1: return selected; break;

    case 2: return selected; break;

    case 3: return selected; break; }

    /* CAPTCHA: muhahaha */

  • dustin (unregistered) in reply to Aerendel

    (defun GetMessage (selected) (cond ((and (> selected -1) (< selected 4)) selected) (0)) )

    I think I might be missing a parenthesis.

  • dolo54 (unregistered)

    private int GetMessage(int selected){ var selectedArray = new Array(); for (var i=0; i<4; i++){ selectedArray.push(i); } return selectedArray[selected]; }

  • (cs) in reply to kvigor
    kvigor:
    Dammit, olsner already beat me to the partial template specialization.

    <nit>Both template solutions use explicit ("total") specializations, not partial ones. "template<>" -> explicit.</nit>

    And what's with the people posting "solutions" that don't preserve semantics?

    edu's only returns the right value for 0-3, and dolo54's doesn't even return if you're outside that range!

  • dolo54 (unregistered)

    lol i'm preserving stupidity... wasn't that the point?

  • Arne Martin (unregistered)

    Here's a new, improved, this time actually working version in Argh!:

    j2 lqphhqphhqphhqphh
    lSjk 01k 12k 23k 34k0
      lXldRXDdRXDdRXDdRXPq

    This time the input is the second character on the first line.

    I love this language.

  • Jon (unregistered)

    In Haskell: getmessage n = let a = \b c d -> if d c b then 0 else c in a 3 (a 0 n (<)) (>)

  • (cs)

    private string GetMessage( int selected ) { return "penguin"; }

    Not particularly useful, but more efficient.

  • BooBoo (unregistered)

    28 lines down to 10 lines and I'll only charge half the cost!

    private int GetMessage( int selected ) { int index=0; switch( selected ) { // Get the Message case 0: index=0; break; case 1: index=1; break; case 2: index=2; break; case 3: index=3; break; } return index; }

    Monk JUSTIN TIMBERLAKE (indirect quote):

    If you give it your all and put in 150%, you're sure to get 100% back.

  • roach (unregistered)

    max(0, min(x, 3))

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

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

    What image? Like the Man says, "Ya know Pepper, ya can't polish a turd."

  • /Arthur (unregistered)

    I think it is a nice example of inline documentation. It's also easy exspandable Who ask's for more

  • muttonchop (unregistered) in reply to VeXocide
    VeXocide:
    All I seem to be missing is an implementation in brainfuck ;)

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

    I haven't tested it, but this should work: ,>+++[->+<<->]<[>>[-]<<-]>>.

  • Mr Python (unregistered)

    Python version:

    def GetMessage( selected ): try: return [0,1,2,3][selected] except: return 0

  • roach (unregistered) in reply to roach
    roach:
    max(0, min(x, 3))

    no wrong

  • muttonchop (unregistered) in reply to muttonchop
    muttonchop:
    VeXocide:
    All I seem to be missing is an implementation in brainfuck ;)

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

    I haven't tested it, but this should work: ,>+++[->+<<->]<[>>[-]<<-]>>.

    Now that I think of it, I could probably simplify that down to: ,>+++[->+<<->]<[>>>]>>.

  • Bjarke Walling (unregistered)

    I heard GAS assembly for X86 is the real thing, so here it goes. As an optimization is doesn't use the stack, nor branching. It is so simple! Only minor bugs I can't find, but I hope it doesn't affect your application. :-)

    /* Input and output in %eax register. */ .globl GetMessage GetMessage: add $0x4, %eax mov %eax, %ebx sub $0x8, %eax mov %eax, %edx sar $0x1f, %edx xor %edx, %eax and $0x1, %edx add %edx, %eax sub %eax, %ebx mov %ebx, %eax sar $0x1, %eax neg %eax mov %eax, %edx mov %eax, %ebx sar $0x1f, %edx xor %edx, %eax and $0x1, %edx add %edx, %eax sub %ebx, %eax shr $0x1, %eax and $0x3, %eax ret

  • Michael (unregistered) in reply to Optimizer
    Optimizer:
    Here's another variant, for flavor.

    private int GetMessage( int selected ) { static const int ONE = 1; int index = 0;

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

    }

    i think i see where you are going, but this function isn't compatibile with the definition of the first (think further the first probably isn't compatible with the definition either, but that is beside the point.)

    private int GetMessage( int selected ) { static const int ONE = 1; int index = 0;

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

    }

    for those who missed it, Optimizer's version gives 0 => 4, 1 => 3, 2 => 2, 3 => 1

    but still good use of select case fall through.

  • T. Hunt (unregistered)
    private static int GetMessage(int selected) {
      List funpool;
      final int obscene = Math.abs(selected) * (selected + 1);
      Object happyfun = new Object() {
        int chosen = obscene >> 1;
        public boolean equals(Object evilbad) {
          return --chosen < 0 || obscene > 13;
        }
      };
      for (funpool = new ArrayList(); !funpool.contains(happyfun); funpool.add(happyfun));
      return funpool.size() - 1;
    }

    I think I'd better stop it before I hurt something/someone.

  • Mike G (unregistered)

    There's ABSOLUTELY NO WTF whatsoever with that code. As "Nicholas" is described as a "contractor", he's probably had more than his fair share of picking up other people's crap code and trying to figure out what it does. And once he's figured out what it does mechanically, he has to figure out how that fits into the logic of the program. By removing any ambiguity whatsoever over the mechanics (it took commenters precisely two comments to notice that it assigned 0 for all values other than 1,2,3) the only thing left to figure out is the logic.

    Pieces of crap code like this:

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

    need to be picked apart and figured out from a mechanical point of view.

    Let me spell it out for you:

    1. Having MORE lines of code for a function does NOTE make it slower
    2. Having MORE lines of code for a function does NOTmake it compile any slower
    3. Having explicit variables instead of implicit temporaries does not make a function run any slower.
    4. There is NO TAX on lines of code, be as explicit as you dare, and then be a little more explicit. The easier you can make your code to understand for others, the better a programmer you are.

    And yes, I have learned that after 22 years of programming.

  • (cs)

    if this is c++ you could do:

    private int GetMessage( int selected ){ return ((unsigned int)selected > 3) : 0 ? selected; }

    other ways envolve: private int GetMessage( int selected ){ return return (selected & (~0x3)) : 0 ? selected; } private int GetMessage( int selected ){ if (selected & (~0x3)) return 0; return selected; }

    private int GetMessage( int selected ){ if ((unsigned int)selected > 3) return 0; return selected; }

    private int GetMessage( int selected ){ if (selected > 3) return 0; if (selected < 0) return 0; return selected; }

    Addendum (2007-01-31 18:39): sorry them : and ? should be the other way around

  • Pointless (unregistered) in reply to Rich
    Rich:
    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

    If it's only branches that need to be avoided and relational oprators are ok, here's a python implementation of abs with no conditionals:

    def new_abs(x): return ((x >= 0) * 2 - 1) * x

    First time posting, apologies if this looks off.

  • deltreme (unregistered)

    Actually it'd better be

    /* enums */ // (...)

    switch (ONE) { case (selected) { return 1; } } switch (TWO) { case (selected) { return 2; } }

  • Nuri (unregistered) in reply to TheRider

    Um what if I pass -3?

  • Nuri (unregistered) in reply to TheRider
    TheRider:
    private int GetMessage( int selected ) { int index = 0;
      for (int counter = 0; counter <= selected; counter++) {
         // Got the Message?
         switch( counter )
         {
    
          case 0:
              index = 0;
              break;
    
          case 1:
              index = 1;
              break;
    
          case 2:
              index = 2;
              break;
    
          case 3:
              index = 3;
              break;
    
        }
      }
      
    
      return index;
    

    }

    Just a little add-on to make it more interesting :-)

    um what if I pass -3?

    • sorry for double post.
  • (cs) in reply to EvanED
    EvanED:
    ...And what's with the people posting "solutions" that don't preserve semantics?

    edu's only returns the right value for 0-3, and dolo54's doesn't even return if you're outside that range!

    Well, the way I see it, a unit test is in order if you want people to supply reasonably correct solutions.

    Translate as needed to your language of choice. Someone should also test the original code to make sure this unit test is correct.

    GetMessage(0) == 0 GetMessage(1) == 1 GetMessage(2) == 2 GetMessage(3) == 3 GetMessage(4) == 0 GetMessage(10000) == 0 GetMessage(-1) == 0 GetMessage(-5) == 0 GetMessage(-10000) == 0

  • Bjarke Walling (unregistered) in reply to triso
    triso:
    Well, the way I see it, a unit test is in order if you want people to supply reasonably correct solutions.

    Translate as needed to your language of choice. Someone should also test the original code to make sure this unit test is correct.

    GetMessage(0) == 0 GetMessage(1) == 1 GetMessage(2) == 2 GetMessage(3) == 3 GetMessage(4) == 0 GetMessage(10000) == 0 GetMessage(-1) == 0 GetMessage(-5) == 0 GetMessage(-10000) == 0

    The assembly routine I posted actually pass this test, but it somehow fails for -1073741825 and below. :(
  • anonymous (unregistered)

    What, no default case!? Oh the horror!

  • me (unregistered)

    In perl : sub boo { (0,1,2,3)[shift] || 0 }

    I.e. test cases from 1 to 10 :

    perl -e 'sub boo {(0,1,2,3)[shift] || 0}; print boo $_ for 0..10 '

    :)

  • brandon (unregistered)

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

  • Mr. Potter (unregistered) in reply to Nanashi

    Jaded? How about incompetent? It is amazing to me how the "programmers" who read this site make fun of these while at the same time posting incorrect code.

  • me (unregistered) in reply to me

    and little bit shorter :

    sub boo {(0..3)[shift] || 0}

    ;)

  • Jon (unregistered)
    def getmessage(n)
      one_two_three = [1, 2, 3]
      if n.to_s.match(/#{one_two_three.map {|i| '^'+i.to_s+'$' } * '|'}/) then n else 0 end
    end
  • (cs)

    Why bother with a function? you could do this as:

    if (($selected > 0) && ($selected < 4)) { $index = $selected; } else { $index = 0; }

    But of course that's just one line, so not much payoff!

  • Zygo (unregistered) in reply to Benanov
    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!

    It only works if the integer type doesn't overflow...

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

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

    OK, put me out of my misery, but what does the ["(c&3)"] do?

    CAPTCHA: ewww --- enough said.

    Ahem. I said it was evil. OK:

    With a string literal we can do

    "abc"[1]

    which is 'b'. But a[b] is the same as b[a], so we could also write

    1["abc"]

    which is also 'b'.

    Now (!(c&~3)) will be 0 or 1 depending on whether c is between 1 and 3, so we get either '(' or 'c', which is then anded with c&3. I'll leave the rest up to you...

    I vote for this one as the hands-down winner. The sheer chutzpah to use almost 1/3 of the code as a string constant used in the code is...breathtaking.

    Just don't compile it on an EBCDIC machine...

  • Zygo (unregistered) in reply to Maks Verver
    Maks Verver:
    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 ...

    Or, you could use a CPU where integer 'abs' is implemented as an instruction. Sure there's conditionals, but they're conditionals etched in silicon...

    I don't remember if x86 is such a CPU, but from the comments here I'm guessing it's not.

  • Tim (unregistered)

    (x*((x&3)==x))

  • Zygo (unregistered) in reply to Rich
    Rich:
    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.

    We're really trying to avoid branches here, since highly pipelined CPU's will stop dead, scratch their heads, then slowly purge their prefetched, partially executed, but now useless instructions before they can start following the branch. Since sizeof(int) and CHAR_BIT typically don't change at runtime, the compiler can evaluate them once and compile the result with no branches.

  • Zygo (unregistered) in reply to Was Anders
    Was Anders:
    from math import pi, ceil

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

    Cute...if the range of values was 0..2 we could use e instead of pi, or cos(0.5) if the range was 0..1.

  • John McCarthy (unregistered)

    I see that nub can't think recursively:

    int GetMessage(int n) {
      return (n <= 0 || n > 3) ? 0 : (1 + GetMessage(n - 1));
    }
  • Grant Hutchins (unregistered)

    Ruby version

    def getMessage(selected)
      Hash.new(0).merge(:message => selected).reject{|key,value|![1,2,3].include?(value)}[:message]
    end
    
  • PoppaVein (unregistered)

    NullSoft Install System (NSIS)

    Function GetMessage Pop $R0 IntCmp $R0 1 0 OutOfRange 0 IntCmp $R0 3 0 0 OutOfRange Push $R0 Return OutOfRange: StrCpy $R0 "0" Push $R0 FunctionEnd

  • Agrajag (unregistered)

    int GetMessage( int selected ) { try { int result = 1 / ( 1 - selected ) / ( 2 - selected ) / ( 3 - selected ); } catch( DivisionByZeroException e ) { return selected; } return 0; }

  • (cs)
    public Double[] SinTable = new Double[91];
    
    private int GetMessage( int selected )
    {
      String paula = "brillant";
      int returnval = new java.util.Random(System.currentTimeMillis() + selected).nextInt() + paula.hashCode();
      switch(returnval * 0 + selected)
      {
      case 0:
        GenerateSinTable(selected);
        returnval = (int)Math.round(SinTable[selected * 1337].doubleValue());
        break;
      case 1:
        GenerateSinTable(selected);
        returnval = (int)Math.round(SinTable[selected * 90].doubleValue());
        break;
      case 2:
        GenerateSinTable(selected);
        returnval = (int)Math.round(SinTable[selected * 45].doubleValue());
        break;
      case 3:
        GenerateSinTable(selected);
        returnval = (int)Math.round(SinTable[selected * 30].doubleValue());
        break;
      default:
        returnval = 0;
      }
      return returnval;
    }
    
    private void GenerateSinTable( int num )
    {
      for(int deg=0; deg<=90; deg++)
      {
        SinTable[deg] = new Double(num * Math.sin(deg));
      }
    }
    
  • woohoo (unregistered) in reply to The Swami of Salami
    The Swami of Salami:
    However silly that function looks, it does map values outside of (1,2,3) to 0.

    well, yes, basically it does... but that's what comparison operators where invented for ;o)

    captcha: craaazy ...... sooo truuueee ;o)

  • (cs) in reply to John McCarthy

    No, No, NO! That's inefficient. Don't you know that you should ALWAYS replace a recursive algorithm that uses O(n) stack space with one using O(lg n)?

    int GetMessage(int n) {
     return (n <= 0 || n > 3) ? 0 : (n & 1 ? 1 + GetMessage(n - 1) : GetMessage(n >> 1) << 1);
    }
    
    John McCarthy:
    I see that nub can't think recursively:
    int GetMessage(int n) {
      return (n <= 0 || n > 3) ? 0 : (1 + GetMessage(n - 1));
    }
  • biff (unregistered)

    index = selected;

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

Leave a comment on “Paid by the Line”

Log In or post as a guest

Replying to comment #:

« Return to Article