Kata: 100 Doors

Grok time ~1 minute

I’ve decided to start doing some code kata.

I can understand C++ code by reading through it, referencing Google and/or running it to double-check what the variables come out to but I haven’t been actively coding enough to keep up with it.

100 doors in a row are all initially closed. You make 100 passes by the doors. The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it). The second time you only visit every 2nd door (door #2, #4, #6, ...). The third time, every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Question: What state are the doors in after the last pass? Which are open, which are closed?

[From Rosetta Code]

Here’s my solution. It’s pretty straightforward but, to be honest, it took me way too damn long. I had forgotten how to do a few things and I also thought that the inner for loop with its statement was all considered one statement, meaning I didn’t need brackets for the outer one with i<PASSES. Took me a bit to fix that. I also really need to work on my mathematics a bit… I know there’s a mathematical way to calculate which doors end up which way because of some property but I don’t know anything about that. Ho-hum.

Luckily, I found an online C++ interpreter to run quick lines through when I want to test things out. I messed up with ++ operator because I forgot it actually saves the incremented value to the variable and is not the same as “x + 1” in an expression; it’s “x+=1”.

#define DOORCOUNT 100
#define PASSES 100

int main() {
	bool doors_open[DOORCOUNT];

	//close doors
	for(int i=0; i < DOORCOUNT; ++i)
		doors_open[i] = false;

	for(int i=0; i < PASSES; i++)
	{
		for(int x=i; x < DOORCOUNT; x+=i+1)
		doors_open[x] = !doors_open[x];
	}
}