Halving Variables



  • Hi all, long time reader first time poster, be gentle :)

    So I like helping people in the Flash forum, you could say I have a passion for it.  Sometimes you get questions which just boggle the mind such as the following, I was sure the first post was a hoax but then they replied with some even better questions.  Here's the original thread and heres their initial question:

    "How would you make a variable (say 6) become half of its original self (as in 3) by the way the variable I need to half is a highscore so it will be differant every time"



  • My 5 year old daughter can work that out, WTF?  I hope this person was not serious..



  • Hard to say if he was serious..

    Considering his posts in other threads are on a higher level, I would say it is a joke or something. On the other hand some of his questions in the thread are serious enough (e.g, the rounding stuff).



  • Damn, I had the perfect solution for him until I saw that requirement that the variable must be different every time.  Now I'm just lost.



  • If it were my guess, the person never passed basic algebra.



  • it really just messed with my head majorly, so many questions kept coming to me like "How do they do their shopping?", "How do they know how much their supposed to get paid?", "How do they pay their bills" and most importantly "How, what, why?!?!"  I did check out some of their other threads to see how those went and whilst at first glance they do seem to be at a slightly higher level than this post when you read further their really just saying words and phrases that they seem to of heard before but didnt realy understand.  Either way I thought it was kinda brave to post the questions that they did.  Got tons of PMs asking WTF?



  • I like how, further down, the question is:

    So if I wanted to make it a qaurter I would change 0.5 to 0.75?

    At least he's trying to understand and take it a step further...



  • [quote user="wgh"]Damn, I had the perfect solution for him until I saw that requirement that the variable must be different every time.  Now I'm just lost.[/quote]

     

    I think I might've come up with your same solution!!! Too bad he can't use it :(

    This only works when the number being halved is 1000

    int answer = Integer.Parse((new String("500")).ToString());

    Oh well!

     

     

     

     

    oh yeah.... I saw a great submission to us from a customer the other day.... 

    strSomeVar = strSomeVar.ToString(); 

    lol ;-P
     



  • The fools!  Wasting all those cycles on floating-point arithmetic!

    score = score >> 1;   will do the job MUCH faster, and only requires the ActionScript coder to understand the principles of two's-complement binary representation, be aware of the bit shift right operator, and plan for an alternate solution for operands that are not powers of 2!

    Signed,

    The Premature Optimizer. 



  • [quote user="GoatCheez"]

    [quote user="wgh"]Damn, I had the perfect solution for him until I saw that requirement that the variable must be different every time.  Now I'm just lost.[/quote]

     

    I think I might've come up with your same solution!!! Too bad he can't use it :(

    This only works when the number being halved is 1000

    int answer = Integer.Parse((new String("500")).ToString());

    Oh well!

    [/quote]

    Well, you could make this work for different variables with a simple switch statement:

     

       switch(score) {

            case 1:               
                   int answer = round(.5);      //round function implementation is left as an exercise         
                   break;
            case 2:
                  int anwer = 1;
                  break;
           .
           .
           .  

          case 1000:
                 int answer = 500;
                 break;
        }
    }



     

     



  • He's probably 10 years old or so, but I still think he's an idiot.
    Nonetheless:
    http://forums.devshed.com/search.php?searchid=1149603

    It's like a WTF Christmas!



  • [quote user="wgh"]Damn, I had the perfect solution for him until I saw that requirement that the variable must be different every time.  Now I'm just lost.[/quote]

     

    No sweat, use a lookup table. Just pick out the values you're most likely to want to divide in half, pre-calculate the dividends, and store it all in a handy table. If you get any values which aren't in the table, just use the nearest neighbor.

     The best part about this approach is you can easily account for special cases, like "oh when he's killed exactly 69 monsters, his score shouldn't be 34.5, but actually 1,000,000, because 69 is a secret cool number." If you had hardcoded an operator like "/", you'd be eating your shoe instead.

     Seriously though, I love the requirement here. WHY does the high score need to be divided in half? In case the player starts getting too good and you want to take him down a notch? Does the game send a screenshot and a webcam grab to the developer so that he can gloat about it?



  • Wow...  I rarely read devshed, but I'm impressed that someone actually helped him.  They must either moderate heavily, or are very friendly over there.



  • Easy solution in Ruby:


    class Numeric
      def half
        self / 2
      end
    end



    6.half => 3

    Man, thank god for open classes...  I don't know how you'd solve this problem any way else.



  • @GneralTsao said:

    Easy solution in Ruby:

    class Numeric
      def half
        self / 2
      end
    end



    6.half => 3

    Man, thank god for open classes...  I don't know how you'd solve this problem any way else.

    But...

    5.half #=> 2 :)
    

    So it should be [b]2.0[/b]



  • Ooh wait! I've got an even BETTER way to halve an integer! Check this one out (who said Ruby was easy to read, anyway?)

    class Fixnum
      alias :old_div :/
      def / d
        d == 2 ? to_s(2)[0..to_s(2).length - 2)].to_i(2) : old_div(d)
      end
    end
    

    150 / 2 # => 75



  • This reminds me of a conversation I had a long time ago with a mainframe assembler programmer.  He had a hex number that he needed to devide by 10 and then print the result using a mask.  The mask is used to format the number; add commas, decimal points, etc.  He was pulling his hair (what ws left) out trying to figure out how to devide a hex number by 10.  He knew how to devide by 2, 4, 8 etc by shifting the bits but could not figure out how to devide by 10.

    Since he was not storing the result anywhere my solution was to just change the mask so that the decimal point appeard one place to the left of where it currently was placed.  A simple change that required no code to implement.  His response to me was "you can't do that!".  So I had him write the values on the white board.  Then I had him manually apply the mask; go figure the value he wrote out was exactly 1/10th of the value stored.  I left him standing there pondering the white board.



  • [quote user="djork"]

    But...

    5.half #=> 2 :)
    

    So it should be [b]2.0[/b]

    [/quote]

    Didn't you read the spec?  It says nothing about needing to support odd numbers!


  • I have a pretty good solution that works for (almost) any number.

    I have grown this code over the years, every time I was presented with a new number I would add it to the switch statement.

    All it takes is patience, years, and a calculator for those difficult ones, like 34672074299912. 
     

    function HalfVariableContainingAnyNumber(variable){

        switch(variable){

            case 1: return 1;

            case 2: return 1;

            case 3: return 2; //remember the rounding requirements.

            case 4: return 2;

            /* snipped almost 80 million lines  */

            case 80000000: return 40000000; 

        } 

    }

     

    In my extensive codebase I halso have really good functions like GetOneQuarterOfAnyNumber() and GetThreeQuartersOfAnyNumber().

    I think I will release my code as opensource and help out all the ppl that have this problem.

     EDIT : Took me so long to post it (stupid meetings) now I notice someone else had my idea as well. Fortunately I patented it over 5 years ago.



  • This is clearly a case of the halves and the halve-nots.

    (Runs away)



  • I remember working on a little flash widget that scrolled through a list of product shots once. I very nearly posted a similar question.

    See the string of product shots had to loop, so I needed to do some arithmetic with the length of the string and it's current offset to figure out when to loop.

    It was all going well until I put four (or some number of items) in the string. Suddenly all the products disappeared. I added some debugging to show the values of all of my variables as the thing ran and, to my surprise, I was informed that:

    2 + 9 = -13

    I double checked and triple checked. Not only that, but

    -1 + -1 = 24.55677 (or some other crazy positive real number)

    So maybe asking how to halve a variable is a bit stupid, but if you ever come across someone asking "how do I increment a variable by another variable", please be patient and suggest the following:

    // increment a and b

    c = 0;

    d = 0;

    if (a > b) {

      c = a;

      d = b;

    } else {

      c = b;

      d = a;

    }

    if ((d == 2)&&(c == 9))

      a = 11;

    // .......... etc

    else

      a = d + c;

    * Note this is based on old flash (2000 i think it was). The story is true, the details have been change to protect me from having to go and track them down. 

     


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.