Skip to content

Instantly share code, notes, and snippets.

@spellgen
Created December 17, 2020 21:01
Show Gist options
  • Save spellgen/f9b8e940d923040546a80711e451ef1f to your computer and use it in GitHub Desktop.
Save spellgen/f9b8e940d923040546a80711e451ef1f to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"os"
"time"
)
type point struct {
x int
y int
z int
w int
}
const (
activeRune = '#'
activeByte = byte(activeRune)
inactiveByte = byte('.')
maxIndex = 1000
)
var deltaList []point // a list of neighbors around a cube
func init() {
deltaList = make([]point, 0)
for w := -1; w <= 1; w++ {
for z := -1; z <= 1; z++ {
for y := -1; y <= 1; y++ {
for x := -1; x <= 1; x++ {
if !(x == 0 && y == 0 && z == 0 && w == 0) {
deltaList = append(deltaList, point{x, y, z, w})
}
}
}
}
}
}
func main() {
t1 := time.Now()
var active = make(map[point]bool)
if len(os.Args) < 2 {
panic(fmt.Sprintf("usage: %s <input>", os.Args[0]))
}
fh, err := os.Open(os.Args[1])
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(fh)
y := 0
for scanner.Scan() {
for x, r := range scanner.Text() {
if r == activeRune {
active[point{x, y, 0, 0}] = true
}
}
y++
}
_ = fh.Close()
for k := 0; k < 6; k++ {
active = step(active)
}
fmt.Printf("part 2: %d cubes are active (%s)\n", len(active),time.Now().Sub(t1))
}
func step(act map[point]bool) map[point]bool {
count := extendedCount(act)
next := make(map[point]bool)
for p, c := range count {
if act[p] {
if c == 2 || c == 3 {
next[p] = true
}
} else {
if c == 3 {
next[p] = true
}
}
}
return next
}
// find the +1 environment around the active cubes
func extendedCount(act map[point]bool) map[point]int {
ext := make(map[point]int)
for p := range act {
for _, d := range deltaList {
ext[point{p.x + d.x, p.y + d.y, p.z + d.z, p.w + d.w}]++
}
}
return ext
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment