• sus
    link
    fedilink
    arrow-up
    88
    ·
    5 months ago

    After working at blizzard for 51 years, I finally found an elegant solution by using the power of recursion

    private bool IsEven(int number){
      if (number > 1) return IsEven(number - 2);
      if (number == 0) return true;
      if (number == 1) return false;
    }
    
      • λλλ
        link
        fedilink
        arrow-up
        14
        ·
        5 months ago

        Now see, you need the other method. IsNegativeEven()

        • sus
          link
          fedilink
          arrow-up
          9
          ·
          5 months ago

          We can avoid expensive branches (gasp) by using some bitwise arithmetic to achieve the so-called “absolute value”, an advanced hacker technique I learnt at Blizzard. Also unlike c, c# is not enlightened enough to understand that my code is perfect so it complains about “not all code paths returning a value”.

          private bool IsEven(int number)
          {
              number *= 1 - 2*(int)(((uint)number & 2147483648) >> 31);
              if (number > 1) return IsEven(number - 2);
              if (number == 0) return true;
              if (number == 1) return false;
              throw new Exception();
          }
          
          • UnknownSoul
            link
            fedilink
            arrow-up
            2
            ·
            5 months ago

            Nice, now we just need another function to find odd numbers, cause not all numbers are even you know.

    • Ebber@lemmings.world
      link
      fedilink
      arrow-up
      13
      ·
      5 months ago

      I removed the tail recursion for you:

      private book IsEven(int number) {
          if(number > 1) return IsEven(number - 2) == true;
          if(number == 0) return true; 
          if(number == 2) return false;
      }
      
      • ulterno
        link
        fedilink
        English
        arrow-up
        3
        ·
        5 months ago

        I didn’t get this.

        Why return book? Does that have some Blizzard reference?
        And why would number == 2return false? This is a function for getting true when the number is even, right?

        • Ebber@lemmings.world
          link
          fedilink
          arrow-up
          12
          ·
          5 months ago

          Haha, you’re right. I’ve now learned two things:

          1. I should not write code on a mobile
          2. I should not become a proof reader

          At the end of the day i just wanted the function to be worse, by causing stack overflows

      • Ferk
        link
        fedilink
        arrow-up
        3
        ·
        5 months ago

        What’d be the result for IsEven(1)?