A Puzzle for a Not-So-Serious Monday
Here, s coding puzzle:
You have 1,000 doors.
You have 1,000 people
The first person is instructed to open all the doors.
The second person is instructed to close every other door.
The third person is to close every third door, if it’s open, or open it if it’s closed.
This repeats until all 1,000 people do their task.
Question: How many doors are now open?
This is the code I came with to solve the problem. I used Excel to avoid array hassles)
Code:
Sub Setup()
For x = 1 To 1000
Cells(x, 1) = "Open"
Next x
End Sub
Sub OpenAndClose()
For y = 2 To 1000
For z = y To 1000 Step y
If Cells(z, 1) = "Open" Then
Cells(z, 1) = "Close"
Else
Cells(z, 1) = "Open"
End If
Next
Next
End Sub
The answer is 31 open doors.
Anyone come up withsomething different?
Re: A Puzzle for a Not-So-Serious Monday
Array hassles?
Code:
Dim i As Long
Dim j As Long
Dim blnOpen(1000) As Boolean
For i = 1 To 1000
For j = i To 1000 Step i
blnOpen(j) = Not blnOpen(j)
Next j
Next i
j = 0
For i = 1 To 1000
If blnOpen(i) Then j = j + 1
Next i
Debug.Print j
Yes, that's the same straightforward approach that you used. Did you happen to notice which doors were left open? They are doors 1, 4, 9, 16... That should be enough to clue you in. It is easy to see why these doors are open while the others are closed. Any door d opened or closed by person p will also be opened or closed by person d/p. This represents both an opening and a closing of the door, except in the case that d/p = p.
The solution for n doors is Int(Sqr(n))
Re: A Puzzle for a Not-So-Serious Monday
Thanks For the analysis. I'd not thought of it that way. Blunt force seemed the way to go. Thanks again
Re: A Puzzle for a Not-So-Serious Monday
MOD - Wouldn't this post be better served in the Code-it Better Forum or the Math Forum?