Monkey and 30 Doors
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-03-24
Problem Statement
Design and implement a system that simulates the “Monkey and 30 Doors” problem. This is a combinatorial problem where a monkey interacts with a sequence of doors (or switches) following a set of rules. The focus is on object-oriented design, modularity, and simulating the behavior accurately.
✅ Problem Statement
1.Setup
•There are 30 doors initially closed.
•The doors are represented as objects or a collection of booleans (true = open, false = closed).
2.Monkey’s Action Rules
•Monkey performs 30 passes over the doors.
•On the i-th pass, the monkey toggles every i-th door (open → closed, closed → open).
•1st pass: toggle every door.
•2nd pass: toggle every 2nd door.
•…
•30th pass: toggle the 30th door.
3.Output
•After 30 passes, determine which doors are open.
•Provide a method:
1
2List<int> getOpenDoors();🔐 Constraints & Assumptions
•Doors are indexed from 1 to 30.
•Toggling is the only allowed operation; no other changes to door states.
•Must support extensibility (e.g., changing number of doors or passes).
•Focus on modular design with clear separation of responsibilities.
🧱 Key Components & Classes
1.Door Class
1
2class Door {
3private:
4 bool isOpen;
5public:
6 void toggle();
7 bool getStatus();
8};1.Monkey Class
1
2class Monkey {
3public:
4 void performPasses(vector<Door>& doors, int totalPasses);
5};1.Simulation / Controller Class
1
2class DoorSimulation {
3private:
4 vector<Door> doors;
5public:
6 DoorSimulation(int nDoors);
7 void runSimulation();
8 vector<int> getOpenDoors();
9};🔄 Example Workflow
1.Initialize 30 doors → all closed.
2.Monkey performs 1st pass → toggles all doors → all doors open.
3.Monkey performs 2nd pass → toggles every 2nd door → doors 2,4,6… close.
4.Repeat until 30th pass.
5.Query getOpenDoors() → returns all doors that are open.
🧪 Expected Deliverables
•Class diagram showing Door, Monkey, and DoorSimulation.
•Implementation of modular classes with proper methods (toggle(), performPasses(), getOpenDoors()).
•Test cases:
•Number of doors = 30 → Verify open doors after simulation.
•Extensible: Number of doors = 50 → simulation works correctly.
💡 Discussion Points
•Why only perfect square numbered doors remain open.
•Extensibility: allow different number of doors or passes.
•Trade-offs between using array vs object-oriented approach.
•Modular design: separation between door state, monkey logic, and simulation control.