Skip to content

Commit 123b79b

Browse files
committed
Add go solution for 100_Doors_Problem
1 parent cc5dd3c commit 123b79b

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func walk() []int32 {
8+
// doors are stored as 32 bit integers
9+
// so we actually store 32 * 4 = 128 doors, but we can ignore the extra ones
10+
doors := make([]int32, 4)
11+
12+
for every := 1; every <= 100; every++ {
13+
for changeDoor := every; changeDoor <= 100; changeDoor += every {
14+
position := uint32(changeDoor % 32)
15+
doors[int(changeDoor/32)] ^= (1 << position)
16+
}
17+
}
18+
19+
return doors
20+
}
21+
22+
func printDoors(doors []int32) {
23+
for i := 0; i < 100; i++ {
24+
element := uint32(i / 32)
25+
position := uint32(i % 32)
26+
if (doors[element]>>position)&0x01 == 1 {
27+
fmt.Printf("%d\n", i)
28+
}
29+
}
30+
31+
}
32+
33+
func main() {
34+
doors := walk()
35+
printDoors(doors)
36+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package main
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestDoors(t *testing.T) {
8+
doors := walk()
9+
10+
squarePointer := 0
11+
perfectSquares := []int{
12+
1, 4, 9, 16, 25, 36, 49, 64, 81,
13+
}
14+
15+
for i := 0; i < 100; i++ {
16+
element := uint32(i / 32)
17+
position := uint32(i % 32)
18+
if (doors[element]>>position)&0x01 == 1 {
19+
if perfectSquares[squarePointer] != i {
20+
t.Fatalf("Door %v is open but should not be.", i)
21+
}
22+
squarePointer++
23+
} else {
24+
if len(perfectSquares) > squarePointer && perfectSquares[squarePointer] == i {
25+
t.Fatalf("Door %v should have been open.", i)
26+
}
27+
}
28+
}
29+
30+
if squarePointer <= len(perfectSquares)-1 {
31+
t.Fatalf("Door %v should have been open, however it is not.", perfectSquares[squarePointer])
32+
}
33+
}

0 commit comments

Comments
 (0)