DEV Community

Cover image for 100 Doors
codeiswine
codeiswine

Posted on • Edited on

3 1

100 Doors

100 Doors

The name's strange but don't fret over it's as easy as making a for loop.

Problem statement :

100 doors in a row are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
And so on it goes up to the 100th time.

First solution

Language: Python

doors = [0] * 100       #initialized all doors to a closed state
for x in range(100):
  for y in range(x, 100, x + 1):
    if (doors[y] == 0):
      doors[y] = 1
    else :
       doors[y] = 0
Enter fullscreen mode Exit fullscreen mode

Well, the amazing thing that caught my eye was that even after a 100 iterations of closing and opening doors the doors which were left open were the perfect squares. (why don't U try it and see the magic for your self)

Second solution

Language: Python

doors = [0] * 100
for x in range(10):
  doors[x * x - 1] = 1
Enter fullscreen mode Exit fullscreen mode

Well, this one's a little funny as I know that all the perfect squares doors are open. I only iterated once and simply opened only those that are perfect squares. (As easy as that.)

For more follow me on Instagram :
id : codeiswine
https://www.instagram.com/codeiswine/

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (1)

Collapse
 
codeiswine profile image
codeiswine

Any other suggestion my ears are open, let me hear them..........

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more