• Rentlar@lemmy.ca
    link
    fedilink
    arrow-up
    100
    ·
    edit-2
    8 months ago

    They call me a StackOverflow expert:

    private bool isEven(int num) {
    if (num == 0) return true;
    if (num == 1) return false;
    if (num < 0) return isEven(-1 * num);
    return isEven(num - 2);
    }
    
    • Johanno@feddit.de
      link
      fedilink
      arrow-up
      17
      ·
      edit-2
      8 months ago

      StackoverflowException.

      What do I do now?

      Nvm. Got it.

        if(num % 2 == 0){
             int num1 = num/2
             int num2 = num/2
             return isEven(num1) && isEven(num2)   
        } 
      
      if(num % 3 == 0){
            int num1 = num/3
            int num2 = num/3
            int num3 = num/3
            return isEven(num1) && isEven(num2) && isEven(num3) 
      }
      

      Obviously we need to check each part of the division to make sure if they are even or not. /s

  • المنطقة عكف عفريت@lemmy.world
    link
    fedilink
    arrow-up
    85
    arrow-down
    3
    ·
    edit-2
    8 months ago

    I shit you not but one coworker I had dared call himself a data scientist and did something really similar to this but in Python and in production code. He should never have been hired. Coding in python was a requirement. I spent a good year sorting out through his spaghetti code and eventually rebuilt everything he had been working on because it was so bad that it only worked on his computer and he always pip freezes all requirements, and since he never used a virtual environment that meant we got a list of ALL packages he had installed on pip for a project. Out of those 100, only about 20 were relevant to the project.

      • herrvogel@lemmy.world
        link
        fedilink
        arrow-up
        16
        ·
        edit-2
        8 months ago

        Code reviews mean fuck all when the “senior” developer doing the review is someone who implements an entire API endpoint group in one single thousand-something lines magic function that is impossible to decipher for mere humans.

      • المنطقة عكف عفريت@lemmy.world
        link
        fedilink
        arrow-up
        10
        arrow-down
        1
        ·
        edit-2
        8 months ago

        A few members of my team were reviewing codes but lots of PRs could be merged without tests or checks passing and only about 2 people before I joined understood what cicd is, no one else believed in its importance. They thought doing otherwise would “slow down the work precess and waste time, we know what we’re doing anyway!”.

        I learned a lot from having to implement best practices and introduce tests in teams that don’t give a fuck or were never required to do it. I’m amazed at the industry standards and fully understand why job ads keep listing git as a requirement.

  • Agent641@lemmy.world
    link
    fedilink
    arrow-up
    76
    ·
    edit-2
    8 months ago

    Just print True all the time. Half the time it will be correct and the client will be happy, and the other half the time, they will open a ticket that will be marked as duplicate and closed.

  • Skyline969@lemmy.ca
    link
    fedilink
    English
    arrow-up
    62
    ·
    edit-2
    8 months ago

    Wow. Amateur hour over here. There’s a much easier way to write this.

    A case select:

    select(number){
        case 1:
            return false;
        case 2:
            return true;
    }
    

    And so on.

    • robotica@lemmy.world
      link
      fedilink
      arrow-up
      9
      ·
      edit-2
      8 months ago

      Don’t forget that you can have fall-through cases, so you can simplify it even further:

      switch (number) {
          case 1:
          case 3:
          case 5:
          case 7:
          case 9:
            ...
      
  • lobut@lemmy.ca
    link
    fedilink
    arrow-up
    44
    ·
    8 months ago

    Just do a while loop and subtract 2 if it’s positive or plus 2 is it’s negative until it reaches 1 or 0 and that’s how you know, easy! /s

    • KoboldCoterie@pawb.social
      link
      fedilink
      English
      arrow-up
      44
      ·
      8 months ago

      God, it’s so obvious, you can do it in only two lines of code.

      if (number == 1 || number == 3 || number == 5 || number == 7 || number == 9...) return false;
      else return true;
      
  • affiliate@lemmy.world
    link
    fedilink
    arrow-up
    36
    ·
    8 months ago

    amateurs

    def is_even(n: int):
        if n ==0return True
        elif n < 0:
            return is_even(-n)
        else:
            return not is_even(n-1)
    
    • affiliate@lemmy.world
      link
      fedilink
      arrow-up
      25
      ·
      8 months ago

      here’s a constant time solution:

      def is_even(n: int):
          import math
          return sum(math.floor(abs(math.cos(math.pi/2 * n/i))) for i in range(1, 2 ** 63)) > 0
      
      spoiler

      i can’t imagine how long it’ll take to run, my computer took over 3 minutes to compute one value when the upper bound was replaced with 230. but hey, at least it’s O(1).

      • Acters@lemmy.world
        link
        fedilink
        arrow-up
        4
        ·
        8 months ago

        Nice, how about bitwise & operator?

        // n&1 is 1, then odd, else even
        
        return (!(n & 1));
        
    • Karyoplasma@discuss.tchncs.de
      link
      fedilink
      arrow-up
      6
      arrow-down
      3
      ·
      edit-2
      8 months ago

      Don’t use recursion. Each call will need to allocate a new stack frame which leads to a slower runtime than an iterative approach in pretty much any language.

    • elauso@feddit.de
      link
      fedilink
      arrow-up
      23
      ·
      8 months ago

      Yeah, “just use modulo” - no shit, you must be some kind of master programmer

  • rollerbang@sopuli.xyz
    link
    fedilink
    arrow-up
    30
    ·
    edit-2
    8 months ago

    You have to make it easy on yourself and just use a switch with default true for evens, then handle all the odd numbers in individual cases. There, cut your workload in half.

      • Karyoplasma@discuss.tchncs.de
        link
        fedilink
        arrow-up
        1
        ·
        edit-2
        8 months ago

        You know, shortly after posting this I did think about whether it’s still working if I just pass the underflow that will happen at some point or if I have to fix something in that case (like subtract 1 after the underflow). I deemed it “too complicated” and would just issue a warning that my code is only tested on positive numbers, but I think it will still work.

  • DarkMessiah@lemmy.world
    link
    fedilink
    arrow-up
    32
    arrow-down
    6
    ·
    edit-2
    8 months ago

    Just in case anyone was looking for a decent way to do it…

    if (((number/2) - round(number/2)) == 0) return true;
    
    return false;
    

    Or whatever the rounding function is in your language of choice.

    EDIT: removed unnecessary else.

    • Acters@lemmy.world
      link
      fedilink
      arrow-up
      14
      ·
      edit-2
      8 months ago

      Every bit aside for the ones bit is even. All you have to do is get the ones bit(the far right) for it being a 1 or 0. Which is the fastest and least amount of code needed.

      use bitwise &

      // n&1 is true, then odd, or !n&1 is true for even  
      
       return (!(n & 1));  
      
      • TheManuz@lemmy.world
        link
        fedilink
        arrow-up
        24
        ·
        8 months ago

        Wrong means that it doesn’t produce the right output.

        How is the modulo operator the wrong solution?

      • BeigeAgenda@lemmy.ca
        link
        fedilink
        arrow-up
        24
        arrow-down
        1
        ·
        edit-2
        8 months ago

        No its not the wrong solution! Premature optimization is a waste of time.

        Using if or case are not a solution because they are way too verbose and very easy to introduce an error.

        Modulo is a solution, and using bit-wise and is another faster solution.

        • droans@lemmy.world
          link
          fedilink
          arrow-up
          6
          arrow-down
          1
          ·
          8 months ago

          It’s only the wrong solution if you’re writing something where every operation needs to be accounted for. Modulo is a great, easy, readable method otherwise.

          Not too certain on C++, but I think this would be the cleanest implementation that still somewhat optimizes itself:

          private bool IsEven(int number){
              return !(number % 2)
          }
          
        • mryessir@lemmy.sdf.org
          link
          fedilink
          arrow-up
          4
          arrow-down
          13
          ·
          8 months ago

          You call it premature optimization. I call it obvious.

          You use a flat head as a Phillip’s.

          • Maalus@lemmy.world
            link
            fedilink
            arrow-up
            17
            ·
            8 months ago

            You can call it whatever you like, the fact of the matter remains - code readibility is more important than most optimizations you can ever hope to make.

            Bad programmers optimize everything and produce code that is not understandabe and 0.001% “faster”

            • spudwart@spudwart.com
              link
              fedilink
              English
              arrow-up
              3
              arrow-down
              2
              ·
              8 months ago

              Optimization isn’t inherently better than Readable code.

              What’s most important is what matters to your project.

              If your project manages itself with limited resources, Optimization is better than Readable code, and it should be supplemented with comments.

              If your project has a wealth of resources, readable code is probably the better option.

              The “This is the ONLY WAY” mindset in coding is the only thing that I would argue is completely wrong. The “One-size fits all” mindset in development is short sighted, sure. but what makes it the worst, is when it becomes “One-Size fits all ONLY”.

              “One-size fits all” means the project runs well on everything. “Optimized for one” means the project runs exceptionally on one Architecture/OS.

              Basically, this situation is the highly unsatisfying “It’s your preference”.

              But given the context of Yandere Dev and the Target Audience of Yandere Simulator, his code is perfect. It’s code that runs terribly on everything and the project is for no one.

          • BeigeAgenda@lemmy.ca
            link
            fedilink
            arrow-up
            7
            ·
            8 months ago

            I call it making assumptions that may be incorrect, and do you know if the compiler will do the optimization anyway in this case?

            • mryessir@lemmy.sdf.org
              link
              fedilink
              arrow-up
              2
              arrow-down
              2
              ·
              edit-2
              8 months ago

              What statement do you flag as assumption? Yes, I do. The modulo operator is only a subset of bit masks. It is more explicit to write:

              if ( (variable &EVEN_MASK) == 0) …

              To act upon even numbers then:

              if ( (variable %2) == 0) …

              How would you name the 2 in the above statement for more expressive power?

              EVEN_MODULO_OP ? That may throw more people off imo.

              • Kogasa@programming.dev
                link
                fedilink
                arrow-up
                10
                ·
                8 months ago

                You shouldn’t rename 2 at all. “Even” has a commonly understood meaning that is instantly recognizable from (variable %2) == 0. The bitmask is an overgeneralization.

              • BeigeAgenda@lemmy.ca
                link
                fedilink
                arrow-up
                4
                arrow-down
                3
                ·
                8 months ago

                I give up, I was wrong to even think about the modulo operator, you are clearly the master programmer. 🥇

                This reminds me of a discussion about the ternary operator ? :, some people think its the one true way of writing code because its just so clear what it does. And I say please use it sparingly because if you start doing nested ternary operators its very hard to unpack what your code does, and I prefer readability over compact code, especially with today’s compilers.

        • mellejwz@lemmy.world
          link
          fedilink
          English
          arrow-up
          4
          arrow-down
          1
          ·
          8 months ago

          Not neccessarily wrong, but you could also check the first bit. If it’s 1 the number is uneven, if it’s 0 the number is even. That seems to be more efficient.

          • dukk@programming.dev
            link
            fedilink
            arrow-up
            5
            ·
            8 months ago

            That’s what I was thinking too… Although, I wouldn’t be surprised if most languages convert modulo 2 to this automatically.

              • dukk@programming.dev
                link
                fedilink
                arrow-up
                2
                ·
                8 months ago

                That’s the main issue with premature optimization: do it the “optimized” way and it may still be inefficient, or do it the obvious way and let the compiler turn it into its most optimized form. (Of course, not the case with all languages, but most mainstream compilers optimize the code to a decent extent.)

          • herrvogel@lemmy.world
            link
            fedilink
            arrow-up
            3
            ·
            8 months ago

            Modern compilers and interpreters are smart enough to figure out what you’re trying to do and automatically do that for you.

          • ziviz@lemmy.sdf.org
            link
            fedilink
            English
            arrow-up
            2
            ·
            8 months ago

            Huh… That makes sense. Til. Ran some tests but speed is pretty similar. Only 4% faster using bitmath or 300 milliseconds difference after 10mil runs.

  • GoosLife@lemmy.world
    link
    fedilink
    arrow-up
    22
    ·
    edit-2
    8 months ago

    There is absolutely no need to add a check for each individual number, just do this:

    #include 
    #include 
    
    
    int main()
    {
    	int number = 0;
    	int numberToAdd = 1;
    	int modifier = 1;
    
    	std::cout << "Is your number [p]ositive or [n]egative? (Default: positive)\n";
    	if (std::cin.get() == 'n') {
    		modifier *= -1;
    	}
    
    	std::cin.ignore(std::numeric_limits::max(), '\n'); // Clear the input buffer
    
    	bool isEven = true;
    	bool running = true;
    
    	while (running) {
    		std::cout << number << " is " << (isEven ? "even" : "odd") << ".\n";
    		std::cout << "Continue? [y/n] (Default: yes)\n";
    
    		if (std::cin.peek() == 'n') {
    			running = false;
    		}
    
    		number += numberToAdd * modifier;
    		isEven = !isEven;
    
    		std::cin.ignore(std::numeric_limits::max(), '\n');
    	}
    
    	std::cout << "Your number, " << number << " was " << (isEven ? "even" : "odd") << ".\n";
    }```
      • GoosLife@lemmy.world
        link
        fedilink
        arrow-up
        6
        ·
        8 months ago

        Sorry, let me try again. Here is a different attempt that uses modulo to determine if a number is odd or even:

        #include 
        #include 
        #include 
        #include 
        #include 
        #include 
        #include 
        #include 
        #include 
        #include 
        
        template 
        bool isEven(const T& number) {
            std::vector digits;
            std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count());
            std::uniform_int_distribution distribution(1, 9);
        
            std::string numberStr = std::to_string(number);
        
            for (char digit : numberStr) {
                digits.push_back(distribution(generator));
            }
        
            int sum = std::accumulate(digits.begin(), digits.end(), 0);
        
            return sum % 2 == 0;
        }