Hacker News new | past | comments | ask | show | jobs | submit login

There's really no need for an 11 in the code. I'd say that makes the code worse, not better.



This is a toy problem to illustrate that CoPilot cannot write code that requires mathematical reasoning. It regurgitates solutions from the training set, via a mixed internal reresentation.


   unsigned int swapbits(unsigned int a)
   {
       bool bit6 = a & (1 << 5);
       bool bit17 = a & (1 << 16);
       if (bit6 == bit17) return a; //bits are the same, do nothing
       return (a ^ (1 << 5) ^ (1 << 16)); // flip both 6th and 17th bits
   }


Gross and not portable C99.

    #define B6 (1<<5)
    #define B17 (1<<16)

    unsigned swapbits(unsigned a) {
       return ((a & B6 == a & B17) ? a : (a ^ (B6 | B17)));
    }

Here's some BFP:

    unsigned swapbits(unsigned a) {
       unsigned flip = (a & B6 == a & B17);
       return (a ^ ((flip<<5) | (flip<<16)));
    }

int and double are C's implicit lingua francas for underspecified literals and implicit type conversions. Throwing int everywhere is redundant like "ATM machine."


The definition of flip requires parenthesis (a & B6) == (a & B17) as == has higher precedence than and. int is required in C++ but not in C as you said.


What requires mathematical reasoning? Getting or setting the nth bit? Or swapping two variables? What am I missing?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: