• Adrian Bool (unregistered)

    If you can't switch a string in your language, I quite like it! Although something more like,

    int helpArg = getHashValue("help");
    int singleArg  = getHashValue("single");
    int mutiArg = getHashValue("multi");
    
    public static void  main (String args[])
    {
        // Get a hash value for the first argument
        int hash = getHashValue(args[0].toCharArray());
    
        switch(hash)
        {
            case helpArg: 
                ...
                break;
            case singleArg: 
                ...
                break;
            case mutiArg: 
                ...
                break;
            // etc
        }
    }
    
  • Meh (unregistered)

    It seems like a reasonable thing to do when you're worried about the length of command-line arguments, or weird command-line injection attacks. This way all the programmer had to worry about was the security of the hashing function (which, in Java, should be fine). And it probably saves some time, I'd guess that hashing and comparing integers is faster (and safer) than string comparison.

  • (cs) in reply to Rich

    I think it might be because java has become less dense than it used to be.

  • Sage Sam (unregistered)

    Here's the C/C++ version..

    I passed this on to a friend of mine who now serves as a CM and--oftentimes--code reviewer. He shared the following lead-in of "platform independent C++ code" that operates the same way (get a number and then use a switch)...

    long value = ((long)((void*)&word)); //word is a char[5]

  • Random (unregistered) in reply to Devi
    Devi:
    That's what happens when a Teacher thinks maintaining their own authority is more important than their students getting accurate information and understanding. I once got into detention at school because of an argument with my science teacher about convection.
    No, you got into an argument about wording, and trying to make things more complex when your teacher's explanation was basically 100% correct, if not as detailed as you might want it.
  • Theo (unregistered)

    The guy should have used a Visitor pattern, easily.

  • Random (unregistered) in reply to Coincoin
    Coincoin:
    Possibilities:
    1. The programmer was told by an overzealous ignorant teacher that if-else-if-else are bad and we should ALWAYS use switch instead.

    switch(strcmp(arg,"foo")) { case 0: { stuff } break; default: switch(strcmp(arg, "bar")) { case 0: { more stuff } break; default: ...

    though, actually, your teacher does have a point. Did you suggest using a binary-search structure of if statements? That can counteract the main reason if-else-if-else is bad (and, yes, it is, even in those cases) for cases when switch won't work.

  • Random (unregistered) in reply to htg
    htg:
    Devi:
    I once got into detention at school because of an argument with my science teacher about convection. She said hot air rose because it was lighter than cold air, I said it rose because the heavier cold air was pulled beneath it by gravity and pushed the hot air upwards.

    1kg of hot air weighs the same as 1kg of cold air :p

    Hot air rises because it is less dense than cold air, and gravity forces the more dense gas under the less dense gas. Hey, if you want to be pedantic!

    Quick! Which weighs more, a gallon of bricks or a gallon of feathers?

    What you're suggesting is that you shouldn't ever be allowed to say one bulk substance is "heavier" than the other.

  • Someone (unregistered) in reply to Random
    Random:
    Quick! Which weighs more, a gallon of bricks or a gallon of feathers?

    If you want to be clever with a question like this, you should probably use an actual weight unit. A gallon is a unit of liquid volume. I imagine if you filled a 1-gallon milk jug with bricks, it would weigh substantially more than the same jug filled with feathers.

  • Aaron (unregistered) in reply to Will

    I actually got apologized to by one of my teachers in second grade when she looked up the "Oxford comma" (putting a comma before the "and" at the end of a list of three or more items) and found out that it was perfectly valid, if optional. She'd insisted it was wrong. (Not that I knew to call it "Oxford comma" back then....)

  • (cs) in reply to htg
    htg:
    The lazy, slow unenergetic particles are hunting for a sofa, pretzels and beer, whilst the energetic fast particles are off achieving great things.

    You write that as if sofas, pretzels, and beer aren't great things.

    Kids--when will they ever learn?

  • Joe (unregistered)

    Maybe he is hiding from the decompiler. When it compiles, it will look like any other compare. You guys know the languages posted on the thedailywtf isn't always the language the code arrived in.

  • Alan Balkany (unregistered)

    " "What's wrong with if else if else if else if else if or some kind of mapping ?"

    "If else if else if else hoses the pipeline a lot with branch instructions." "

    The switch statement would also have the branch instructions when compiled into machine code. The only difference is how the high-level-langugage constructs look before they're compiled.

  • Alan Balkany (unregistered)

    " "What's wrong with if else if else if else if else if or some kind of mapping ?"

    "If else if else if else hoses the pipeline a lot with branch instructions." "

    The switch statement would also have the branch instructions when compiled into machine code. The only difference is how the high-level-langugage constructs look before they're compiled.

  • gygax (unregistered) in reply to Aaron
    Aaron:
    I actually got apologized to by one of my teachers in second grade when she looked up the "Oxford comma" (putting a comma before the "and" at the end of a list of three or more items) and found out that it was perfectly valid, if optional. She'd insisted it was wrong. (Not that I knew to call it "Oxford comma" back then....)
    Interesting, when I was in 2nd grade (1980) I was taught this was the only correct way.
  • dolo54 (unregistered) in reply to Will
    Will:
    Devi:
    I once got into detention at school because of an argument with my science teacher about convection. She said hot air rose because it was lighter than cold air, I said it rose because the heavier cold air was pulled beneath it by gravity and pushed the hot air upwards. Being an arrogant little ***** I refused to back down and spent 3 hours writing lines for my trouble.

    I was scolded twice by my fifth-grade teacher for saying that 2 was a prime number. She held that it was a composite number "because it was even."

    I was told by my third grade teacher that I was "too smart for my own good" because she was telling the class that possums were smart animals because they would play dead when a predator was near and I corrected her (I had just read about it in Ranger Rick) that possums aren't that smart... they actually faint from fear when they smell the predator.

  • Jim Rowell (unregistered)

    I can't believe everyone thinks this is whacked code. Hashing strings before entry into a case statement is a common construct when there are a huge quantity of strings that must be compared. The overhead of the hash function is small compared to the increased speed delivered by only having to compare numbers rather than strings. It can also be done before entering an actual search routine as opposed to the simple case statement of the example.

    You could argue it will almost always be over-optimising but there are times when it makes sense. It might be a wtf but without knowing what follows the "etc" we have no way of knowing.

    As for the concern that the hash function will allow collisions... that's valid but again, we havn't seen the whole routine. Collisions can be checked for when the danger warrants it. This can be done at design time or after passing through the function.

  • Darien H (unregistered)

    He's writing in Java. Java does not "switch" on objects (like Strings), because of the various complexities of what is object.equals() for different objects etc.

    If I had to write similar code today, I'd use Java Enums, as of version 1.5, which CAN be put into a switch statement and look a heck of a lot nicer.

    I'd justify that choice by saying that these are command line arguments--they are tokens of a small fixed known supported set that won't change during runtime. Furthermore, it might be handy to associate other information with them, such as a list of other arguments that are mutually exclusive or are also required, etc.

    Go easy on me, I haven't programmed in Java in months... it's been PHP/Python season. Anywho, building off of Adrian's example:

    // Makes for loose coupling, since string representation can be changed
        // without changing the logic everywhere
        public enum CmdArgs {
    	HELP    ("help"),
    	SINGLE  ("single"),
    	MULTI   ("multi");
    
    private final String stringrep;
    CmdArgs(String representation) {
        this.stringrep = representation;
    }
    public String getStringRep() { return stringrep;}
    }
    
    public static void  main (String args[])
    
    {
    
    String firstArg = args[0];
    
    // Find the right enum based on textual representation
    CmdArgs myenum = null;
    for(CmdArgs enumversion : CmdArgs.values()){
        if(enumversion.getStringRep().equals(firstArg)){
    	myenum = enumversion;
    	break;
        }
    }
    if(myenum == null){
        // Temper tantrum! Argument incorrect!
        return;
    }
    
    
    
    switch(myenum){
    
        case HELP: 
    	//TODO
    	break;
    
        case SINGLE: 
    	//TODO
    	break;
    
        case MULTI: 
    	//TODO
    	break;
    
        // etc
    
    }
    

    Captcha: "Muhahaha I'm in ur JVM, nulling ur pointerz"

  • Mike (unregistered) in reply to gygax
    gygax:
    Aaron:
    I actually got apologized to by one of my teachers in second grade when she looked up the "Oxford comma" (putting a comma before the "and" at the end of a list of three or more items) and found out that it was perfectly valid, if optional. She'd insisted it was wrong. (Not that I knew to call it "Oxford comma" back then....)
    Interesting, when I was in 2nd grade (1980) I was taught this was the only correct way.
    I learned it was optional at one school, then got told not using the comma was preferred at another school. I always liked it because I thought it made lists like this more clear: "...apple, chips, and peanut butter and jelly."
  • (cs) in reply to Jim Rowell
    Jim Rowell:
    I can't believe everyone thinks this is whacked code. Hashing strings before entry into a case statement is a common construct when there are a huge quantity of strings that must be compared. The overhead of the hash function is small compared to the increased speed delivered by only having to compare numbers rather than strings. It can also be done before entering an actual search routine as opposed to the simple case statement of the example.

    You could argue it will almost always be over-optimising but there are times when it makes sense. It might be a wtf but without knowing what follows the "etc" we have no way of knowing.

    As for the concern that the hash function will allow collisions... that's valid but again, we havn't seen the whole routine. Collisions can be checked for when the danger warrants it. This can be done at design time or after passing through the function.

    We think its whacked out code because its horrible to maintain.

    If this is reading in command line arguments, the amount of time saved in using the hashtable algorithm is lost in the cost of starting the program up.

    As for collisions, well there is always the danger of them, and they aren't checked. We see the first item is "help". But how do we know that "helpme" doesn't map to the same thing as "format ."?

  • Jim Rowell (unregistered) in reply to chrismcb
    chrismcb:
    We think its whacked out code because its horrible to maintain.

    If this is reading in command line arguments, the amount of time saved in using the hashtable algorithm is lost in the cost of starting the program up.

    As for collisions, well there is always the danger of them, and they aren't checked. We see the first item is "help". But how do we know that "helpme" doesn't map to the same thing as "format ."?

    Yes, it's not optimum for maintenance and that's one reason why it should only be done when there is a speed issue due to the volume of strings being compared.

    There will be zero noticable extra time needed to start the program. The hash function should return in a few milliseconds. If it doesn't, it's not a very good hash function. There will only be a single string to be hashed and typically hundreds of possible hashes to be searched. That's why directly comparing hundreds of strings would be a true wtf.

    Collisions aren't checked in the tiny part of the function we were given. You don't know what the real function ends up doing. Anyway, the expected strings can be checked at design time to ensure no collisons. Non-expected strings (bad input) stand only a very remote chance of reporting a false match and checking for collisions is probably not even warranted. For most applications, the fact that a wrong input was entered AND then managed to slip through as something else would not be a huge issue if it only were possible 1 out of a few million times. You'd have to actually be a guy who buys lottery tickets to worry about it. <g> Depends on the application, of course.

    I'll admit it's a bit unusual to need it for command line parsing. There aren't usually enough command line options that an app would be interested in.

    I've never had to use it and I think I'd first try alternate methods such as a simple binary search but it IS a legit method rather than an automatic wtf.

  • Marko (unregistered) in reply to Mike
    Mike:
    I learned it was optional at one school, then got told not using the comma was preferred at another school. I always liked it because I thought it made lists like this more clear: "...apple, chips, and peanut butter and jelly."

    Wtf? You are eating your chips with peanut butter? You must be British to pull that.

    CAPTCHA: gotcha (how appropriate)

  • forgotten (unregistered)

    It looks like the snippet is generated by something like http://www.gnu.org/software/gperf/gperf.html Not a wtf at all imho. Its automatically generated code, nothing that needs to be readable.

  • zproxy (unregistered) in reply to diaphanein

    C# compiler will convert a string switch to a hashtable - which means there is no actual wtf here - move along.

  • Armchair Math Dork (unregistered) in reply to Devi
    The one that always upset me was one, I mean the rules say it must be "Only divisible by itself and one", some people seem to think it gets disqualified because itself and one are the same thing. Like it's cheating and has an unfair advantage or something...

    If one were prime, then positive integers would not have unique prime factorizations. 100 for example could break into 2^2 * 5^2, as well as 2^2 * 5^2 * 1 and 2^2 * 5^2 * 1 * 1... and so on. "Itself and one" is a pretty poor definition for prime numbers really.

  • Dhericean (unregistered) in reply to Random
    Random:
    Quick! Which weighs more, a gallon of bricks or a gallon of feathers?

    More interesting question - Which is heavier a pound of feathers or a pound of gold?

  • (cs) in reply to Meh
    Meh:
    It seems like a reasonable thing to do when you're worried about the length of command-line arguments, or weird command-line injection attacks. This way all the programmer had to worry about was the security of the hashing function (which, in Java, should be fine). And it probably saves some time, I'd guess that hashing and comparing integers is faster (and safer) than string comparison.
    Am pretty sure it save no time, because hash need to go to all the String characters to have a value, while arg[0].equals("help") will stop fast if String are not of equal length (first comparaison which is enough to detect most unequal strings) or return at first character not same (unless unequals character are deep in end of long equal length strings, this will go fast). Moreover, unequal strings can have equal hashcode using the java string hashcode:
    (from an english dictionary) -677896684: fineable, unapprehending -982749752: dentinalgia, poised 427589249: hypoplankton, unheavenly -1064558421: agarwal, hazardless -1166076941:acouasm, kindergartener

    If you are really worried about using integer based operation to save time, by using some hashing code, i'd recommend this, which is cleaner and has the comparaison optimization:

    public static void  main (String args[])
    {
        String arg=args[0].intern();
        if (arg == "help"){
          ...
        }
        else if (arg == "single"){
          ...
        }
        else if (arg == "multi"){
          ...
        }
    

    }

    Note: Before throwing heavy things at me saying you can't compare Strings with == operator in java and that i'm an ass, check the api specification of intern() :) For those not used to java, the == operator compare object instance , not it's content. So, it's generally a bad idea to use == operator to compare String object, but intern() is magic :p

  • (cs) in reply to Armchair Math Dork
    Armchair Math Dork:
    The one that always upset me was one, I mean the rules say it must be "Only divisible by itself and one", some people seem to think it gets disqualified because itself and one are the same thing. Like it's cheating and has an unfair advantage or something...

    If one were prime, then positive integers would not have unique prime factorizations. 100 for example could break into 2^2 * 5^2, as well as 2^2 * 5^2 * 1 and 2^2 * 5^2 * 1 * 1... and so on. "Itself and one" is a pretty poor definition for prime numbers really.

    from wikipedia(en):
    prime number (or a prime) is a natural number that has exactly two (distinct) natural number divisors, which are 1 and the prime number itself. There exists an infinitude of prime numbers, as demonstrated by Euclid, in about 300 B.C.. The first 30 prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, and 113
  • Watson (unregistered) in reply to Will
    Will:
    Devi:
    I once got into detention at school because of an argument with my science teacher about convection. She said hot air rose because it was lighter than cold air, I said it rose because the heavier cold air was pulled beneath it by gravity and pushed the hot air upwards. Being an arrogant little ***** I refused to back down and spent 3 hours writing lines for my trouble.

    I was scolded twice by my fifth-grade teacher for saying that 2 was a prime number. She held that it was a composite number "because it was even."

    I remember a teacher of mine who insisted that zero is not an even number. Nor is it an odd number, apparently. We were supposed to call it a "neutral" number. I can only surmise that something garbled about "natural numbers" might have passed within his ken at some stage.

  • Watson (unregistered) in reply to xix
    xix:
    I always go by the prime decomposition. 1 is an irritating prime since then you have an infinite number of prime decompositions for any composite number. 1 itself it not prime, nor is it not prime since it's decomposition is just itself, so one is the special.

    Now 2, just ask the teacher for the multi-term prime decomposition of 2.

    captcha: burned (well, quite)

    (Yes, I'm blending two misapprehensions: "1 is a prime number" and "2 is not a prime number".)

    Well, if 1 is a prime number it's easy: 2 = 2×1×1×1×1×1.... Oh, wait. I guess 2 is composite after all. Now, what about 3....?

  • Sid (unregistered) in reply to Dhericean

    A pound of feathers. The pound of gold (troy) is 12 ounces, while the pound of feathers (avoirdupois) is 16.

  • DaRamirez (unregistered)

    I come here like every day at midday to either learn something or have a good laugh but today I almost split my drink all over my keys when I saw this piece of code.

    It remembers me of my self always wanting to invent new ways of "improving" certain things...

    I thank you allot for the good laugh

  • cy (unregistered) in reply to Devi

    1 cannot be prime or the uniqueness decomposition theorem goes out of the window.....

  • Random (unregistered) in reply to Sid
    Sid:
    A pound of feathers. The pound of gold (troy) is 12 ounces, while the pound of feathers (avoirdupois) is 16.

    Ah. Now, what weighs more, an ounce of gold or an ounce of feathers?

  • Random (unregistered) in reply to Someone
    Someone:
    Random:
    Quick! Which weighs more, a gallon of bricks or a gallon of feathers?

    If you want to be clever with a question like this, you should probably use an actual weight unit. A gallon is a unit of liquid volume. I imagine if you filled a 1-gallon milk jug with bricks, it would weigh substantially more than the same jug filled with feathers.

    I was being clever. A weight unit is expected in the standard form of that question, which I inverted. I was pointing out the flaw in refusing to say that cold air can't be heavier than hot air.

    dolo54:
    I was told by my third grade teacher that I was "too smart for my own good" because she was telling the class that possums were smart animals because they would play dead when a predator was near and I corrected her (I had just read about it in Ranger Rick) that possums aren't that smart... they actually faint from fear when they smell the predator.

    What is the difference? You can't really attribute "smart" or "fear" to a non-sapient animal, and from an evolutionary point of view they're the same in this instance. Actually, I'd go so far as to say that a justified fear is always the same as "smart" from an evolutionary point of view.

    captcha kungfu

  • Random (unregistered)

    (obTRWTFITFS: post was eaten. new captcha: yummy)

    Someone:
    Random:
    Quick! Which weighs more, a gallon of bricks or a gallon of feathers?

    If you want to be clever with a question like this, you should probably use an actual weight unit. A gallon is a unit of liquid volume. I imagine if you filled a 1-gallon milk jug with bricks, it would weigh substantially more than the same jug filled with feathers.

    I was being clever. A weight unit is expected in the standard form of that question, which I inverted. I was pointing out the flaw in refusing to say that cold air can't be heavier than hot air.

    dolo54:
    I was told by my third grade teacher that I was "too smart for my own good" because she was telling the class that possums were smart animals because they would play dead when a predator was near and I corrected her (I had just read about it in Ranger Rick) that possums aren't that smart... they actually faint from fear when they smell the predator.

    What is the difference? You can't really attribute "smart" or "fear" to a non-sapient animal, and from an evolutionary point of view they're the same in this instance. Actually, I'd go so far as to say that a justified fear is always the same as "smart" from an evolutionary point of view.

  • Random (unregistered) in reply to tchize
    tchize:
    Note: Before throwing heavy things at me saying you can't compare Strings with == operator in java and that i'm an ass, check the api specification of intern() :) For those not used to java, the == operator compare object instance , not it's content. So, it's generally a bad idea to use == operator to compare String object, but intern() is magic :p

    It's not magic, it's lots of hard work concealed behind the scenes. How do you think it works, if not by comparing the string to every string already in the string pool, not even only the ones you're testing for.

    captcha: stinky

  • Darien H (unregistered)

    Random's right... Using String.intern() for strings in place of String.equals() in this case is a WTF unless you literally need to be certain it's the same String object in memory. Unlikely.

  • Anonymous (unregistered) in reply to Devi
    Devi:
    I once got into detention at school because of an argument with my science teacher about convection. She said hot air rose because it was lighter than cold air, I said it rose because the heavier cold air was pulled beneath it by gravity and pushed the hot air upwards.
    The WTF in your story is that neither your teacher nor you can realize that both "explanations" are equivalent. It's just like A arguing with B, just because A thinks "3>2" and B thinks "2<3".
  • Anonymous (unregistered) in reply to TheRider
    TheRider:
    Devi:
    She said hot air rose because it was lighter than cold air, I said it rose because the heavier cold air was pulled beneath it by gravity and pushed the hot air upwards.
    What a great way of thinking. Looking at it that way never occurred to me so far. Absolutely brilliant! But, aren't these two views just two sides of the same coin? (Yes, I *do* understand that the former is a rather simplistic view oriented towards our "everyday life experience" whereas the latter is a more scientific view reflecting actual laws of physics.)
    I don't agree with you. I don't find the "cold air sinks" version reflect physical laws more than the "hot air rises" one. You may have "gravitational pull" in mind. But what if the teacher has "Archemedes principle" (of buoyancy) in mind? Which is "more scientific", then? And how about the following alternative explanation?

    Every system has a tendency to lower its potential energy -- until it has reached the minimal P.E. state. If a system is not at a minimal P.E. state, it will rearrange itself to lower its P.E. until a minimal is reached.

    Now, how do we apply the "physical law" stated in the paragraph above to the example with hot/cold air? Just examine the gravitational potential energy of a system of hot and cold air in a gravitational field. Which state has a higher potential energy: hot air above cold air, or cold air above hot air? Now, you should see why, according to the "law" stated in the paragraph above, cold air sinks and hot air rises: The system is simply rearranging itself to lower its (gravitational) P.E. That explanation simultaneously explains why hot air floats (buoyancy) and cold air sinks (gravitational pull). Indeed, quantitatively, you can compute the force acting on the objects in the system: rate of change of P.E. is equal to the force.

    Now, which explanation is better? It's just like asking which side of a coin is better. It's a meaningless question.

  • Anonymous (unregistered) in reply to Greg
    Greg:
    Actually, you were both wrong.
    I would not say you're wrong. But I'm sure you're _not more correct_ than the others:
    Greg:
    It has to do with density. The same reason oil floats on water.
    But why do you say "oil floats on water", and not "water sinks in oil"? Do you think there is really a physical and scientific difference between these two statements? Or are you simply hydrocentric?

    See my other posting. I can explain why oil tends to stay above water (or water tends to stay below oil) by a simple principle: a system rearranges itself to lowers its (gravitational) potential energy until the total P.E. of the system is minimized. It's not hard to realize that the state in which all oil molecules stay above all water molecules minimizes the P.E. of a water-oil system.

    Greg:
    Hot air is less dense than cold air because the air molecules have more energy, etc etc. Bust out a physics book.
    Using my "P.E. minimization" approach, I would say "cold air sinks" or "falls" because it has higher (gravitational) potential energy. Is there anything wrong with that? Why are you only giving concentration to the hot air molecules?

    While "density difference" is the usual approach to this physical phenomenon taught it textbooks, there are alternative approaches to explain the same thing, such as the "minimization of P.E.". Both explanations are valid and useful.

    Those who assume that there can be only one approach are too naive.

  • Anonymous (unregistered) in reply to gusmao
    gusmao:
    There is yet another gotcha. Since the return value of hashfunctions may collide, depending on the values of the String passed as argument he can have two different options being resolved into the same case.
    Why not do an extra check for equality inside each case? Doesn't java.util.HashMap do that check, too?

    The WTF here is that the programmer didn't reuse what's already written, tested and debugged in java.util.HashMap (or String.hashCode()).

    gusmao:
    Granted, that's unlike to happen, but it nevertheless can introduce a very subtle and pernicious bug into the program.
    Why do you assume it's unlikely to happen?

    The code snippet shows that it is not using the standard String.hashCode() function in Java. Instead, it is using a customized getHashValue() function. And we know absolutely nothing about this function. This function could be written so badly that it clashes often. e.g. rather than exploiting the full 32-bit range of the Java int type, this function may be returning a value that only varies in its lowest 3 bits. In that case, collision is 1 part in 8, or 12.5%, which I won't consider "unlikely".

    But of course, if that hash function is generated by the "gperf" utility, it is likely that the probability of collision is ZERO. In that case, the program is a genius.

  • Anonymous (unregistered) in reply to ToxikFetus
    ToxikFetus:
    It doesn't matter where you put the resistor, the voltage drop across each element remains the same. Thus, the current through each element is fixed, meaning the LED would fry or not fry in any configuration, depending on the component values.

    Really? In any configuration?

    Try to apply a DC of 100kV across this combination and see if you get smoke!

    Even with a simple resistor, you cannot say its voltage drop is fixed. What is fixed for a resistor is the resistance (measured in Ohms), not the voltage drop (measured in Volts). The voltage drop across a resistor is current*resistance. It does depend on current. And how large a current can you create? It depends on the voltage of the power supply.

  • Michel Colman (unregistered) in reply to Will

    2 is not a prime number because it is even. By the same rule, 3 is not a prime number either, as it is a multiple of 3. Neither is 5, etc. In short, prime numbers simply do not exist. This is a brilliant discovery!!!

    OK, back to reality. 1 is not a prime number because it only has one positive divisor, not two. This makes sense if you consider the main purpose of prime numbers. They can be used to give a unique decomposition of any number, for example 156 = 2^2 * 3^1 * 13^1. If 1 was a prime, there would be an infinite amount of decompositions possible because you can add any power of 1 without changing the result. Prime numbers are the building blocks for making numbers by multiplication. Multiplying by 1 does not get you anywhere, so it is not considered a prime. Look up "prime" on wikipedia if you don't believe me, you'll find all sorts of other uses for primes where 1 would be completely out of place.

    As for 1 not being a composite number, think again. It's just the zero'th power of any prime. (In fact, the prime decomposition is an infinite series of powers of all primes, with only a finite amount of the powers not equal to zero, and in the case of 1 they are simply all zero).

    Zero is the only nonnegative integer that does not have a prime decomposition.

    As for hot air and cold air: a gas is just a bunch of molecules flying around at high speed, hitting each other and all sorts of nearby surfaces. The "gas laws", using density, pressure, etc., are really just very good statistical approximations. For example, pressure is the average force caused by the zillions of collisions per second of gas molecules with a unit surface. Temperature is related to the average kinetic energy of the molecules. If you increase the temperature, the molecules will hit nearby surfaces more frequently and at higher speed, so we say pressure goes up. Increase the volume (by moving a wall away from the gas) and the molecules hitting the retreating wall will bounce back with less energy, decreasing the average temperature. Believe it or not, it works out perfectly if you do the math, resulting in laws like "p = rho r t" that we all know and love. It's called ideal gas theory (which is itself just a pretty good approximation because gases are not really ideal in reality, collisions are not perfectly elastic, viscosity is not accounted for, etc.).

    So the beautiful analogy with lazy molecules going for the couch and energetic molecules going up to achieve great things is the most realistic view imho.

    Anyway, what was this thread about again? O, using hashes in a switch statement? Well, the main problem is that a user might type something like "yqsfolihqsd" and the hash just happens to be the same as that for "help", resulting in unexpected behaviour. The problem is unlikely to cause problems (compile errors) during development, though, because all valid commands are likely to have different hashes.

    The main missing bit is that, in each case clause, the full string should be verified to make sure it is not a different string that happens to have the same hash.

    Other than that, I don't think this is such an extremely bad idea. If you have lots of strings, this may even be one of the most efficient ways of handling them. After all, the C++ standard library does offer hash tables too, doesn't it? Then again, if it's only a few commands, the overhead of the hashing function is likely to offset any gains in switching performance.

    Then again, does performance really matter for something that's used only once per application run anyway?

  • Michel Colman (unregistered) in reply to J.
    J.:
    I've had the opposite. One of my university lecturers in introductory programming told us using switch was bad because "it's almost like using goto". I stopped attending his lectures after that.
    I never use statements like "if", "for", "while", etc. because they are almost like using goto too. Granted, it makes coding a little bit more difficult, but at least I can rest assured that my code is clean and easy to maintain.
  • airdrummer (unregistered) in reply to Devi

    i had the same ignorant asshole teacher in 4th grade: she insisted that the answer to "could timmy feel the heat of the burning barn?" was no because that's what the answer key said, and hot air rises:-(

  • (cs)

    I found something very similar in some code parsing a xml file recently in our codebase. It did this to match element names with the values of an enum.

    It was written based on brilliant advices from one of our worse premature optimizers (who is also unfortunately the lead coder of an important module of the project): "it's the fastest way to do it!!1!")

    Those were pretty small xml files containing only a few elements by the way.

  • Zemm (unregistered) in reply to Anonymous
    Anonymous:
    ToxikFetus:
    It doesn't matter where you put the resistor, the voltage drop across each element remains the same. Thus, the current through each element is fixed, meaning the LED would fry or not fry in any configuration, depending on the component values.

    Really? In any configuration?

    Try to apply a DC of 100kV across this combination and see if you get smoke!

    Even with a simple resistor, you cannot say its voltage drop is fixed. What is fixed for a resistor is the resistance (measured in Ohms), not the voltage drop (measured in Volts). The voltage drop across a resistor is current*resistance. It does depend on current. And how large a current can you create? It depends on the voltage of the power supply.

    Simple: get a 5 megaohm resistor. V=IR. R=V/I. A LED has a ~2V drop and requires ~20mA. R=100000/0.02=5000000. Hows this any different? :) Of course this is ignoring the (im)practicalities of pumping that much voltage through such small devices, and that the resistor would have to disipate 2kW (P=VI) to get the voltage to drop that much. A very long cable should do it!

    (Sorry if my maths is off, it is past 2am here and I should have been in bed hours ago but I sometimes get stuck reading interesting websites)

    o---VVV---|>|---o is the same as o---|>|---VVV---o for a given problem. (Mmm ASCII art)

  • GiggleStick (unregistered) in reply to Devi

    Yes, but even though that teacher was douche, he inadvertently taught you a lesson. Many authority figures are morons and your best bet is to find a way to circumvent them to get to the real solution.

  • kstephens (unregistered)

    I've inherited some code that did something similar in C for long lists of nested switches. It's far more maintainable, but it is still kinda perverse:

    int strsum(const char *s)
    {
      int i = 0;
      while ( *s ) {
        i += *(s ++);
      }
      return i;
    }
    
    ...
    
    switch ( strsum(str) ) {
      case 'f'+'o'+'o':
        foo();
        break;
      case 'b'+'a'+'r':
        bar();
        break;
      default:
        error();
        break;
    }
    
    

    Compiler catches collisions of the hand-coded case hashes, but "foo", "oof" and "nog" are indistinguishable. Fine if your inputs are constrained to a known valid set.

Leave a comment on “Classics Week: How Not to Parse Command Line Arguments”

Log In or post as a guest

Replying to comment #:

« Return to Article