Created
October 28, 2023 00:30
-
-
Save bsidhom/c5b21d74e681ce5dd6495c9a9cc17b55 to your computer and use it in GitHub Desktop.
100 switches/100 lights puzzle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Solves https://www.youtube.com/watch?v=ltsx5389iEs | |
# The idea is to identify all lights in ⌈log2(n)⌉ moves by assigning each bulb | |
# an integer and using the unique bit representation of each as the sequence of | |
# light switches for which it was powered on (1 means it was on for a given | |
# trial, 0 means it was off). | |
# NOTE: The bit representation + transpose operation makes the logic most clear, | |
# but you can also generate this code in other ways (e.g., by applying a "01" | |
# pattern to each half of the previous pattern recursively). There are also many | |
# equivalent codes (which you can generate by permuting the number assignments | |
# before transposing or swapping out bulb numbers up to the next power of 2 | |
# where the number of bulbs is not a power of 2, or similarly reordering the | |
# switches). | |
import math | |
def main(): | |
for pattern in transpose(bitmasks(100)): | |
print("".join(pattern)) | |
def transpose(it): | |
return zip(*it, strict=True) | |
def bitmasks(n): | |
size = math.ceil(math.log2(n)) | |
spec = f"0{size}b" | |
for i in range(n): | |
yield format(i, spec) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment