Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

    days = 28 + ((0x3bbeecc>>(month*2))&3);


I like yours for the minimum number of operations needed:

    28+((0x3bbeecc>>(m*2))&3)
But here's my own attempt anyway, which wins on number of characters typed =)

    30+(m&1^m>7)-m*(m==2)


Where does this come from?


The basic idea is to encode the array within a single integer:

   0 + [anything, 31,28,31,30,31,30,31,31,30,31,30,31]
  28 + [anything,  3, 0, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3]
              00, 11,00,11,10,11,10,11,11,10,11,10,11

   reverse:   11,10,11,10,11,11,10,11,10,11,00,11, 00
            0011  1011  1011  1110  1110  1100   1100
          0x   3     b     b     e     e     c      c   
We have 4 possible values in the array, so we need 2 bits per value. We have one dummy value + 12 required values, so we need a total of 2*13 = 26 bits which fits easily into a 4 byte integer (either 32 bits unsigned or 31 bits signed). To retrieve one element from the "array", we need to shift our constant 2 bits per month or twice by the numer of months. Then we need to mask everything but the lowest 2 bits (&3).


Great explaination. This is the sort of post that makes me love HN.


It basically just stores [3, 0, 3, 2, ...] as 2-bit numbers, and the shift then corresponds to indexing.


Wow that's very clever!




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

Search: