36/42
Part 8 of 8 · Follow-upsLearn and do
A calendar as the bits of one integer: one AND checks a stretch of days
The practice problem's follow-ups ask for a bitmask version. Give each day a bit. 1 << day shifts a 1 left by day places, so 1 << 3 is 8, 0b1000: a number whose only set bit is bit 3. Adding one of those per free day gives one bit per day. (1 << k) - 1 is k ones in a row, and shifting that left by lo moves them onto days lo to hi:
ana_free = sum(1 << day for day in {1, 2, 3, 6, 7})
# one bit for each day lo through hi
def days_mask(lo, hi):
return ((1 << (hi - lo + 1)) - 1) << lo
print(ana_free, bin(ana_free))
print(days_mask(1, 3), days_mask(1, 4))
print(ana_free & days_mask(1, 3) == days_mask(1, 3))
print(ana_free & days_mask(1, 4) == days_mask(1, 4))
print(ana_free.bit_count())
206 0b11001110
14 30
True
False
5
ana's free days {1, 2, 3, 6, 7} become 0b11001110, which is 206. Days 1 through 3 are the mask 0b1110, 14.
206 & 14: what does the AND give, and is ana free on days 1 through 3?
Pick an answer above to see the rest