Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 17, 2020 10:44
Show Gist options
  • Save felix-larsen/10eddfa2e8f03bb159f2aa62f38fa7c0 to your computer and use it in GitHub Desktop.
Save felix-larsen/10eddfa2e8f03bb159f2aa62f38fa7c0 to your computer and use it in GitHub Desktop.
17th December solution - Advent of Code 2020 - swift
import Foundation
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december17.txt"
let contents = try! String(contentsOfFile: filename)
let lines = contents.components(separatedBy: CharacterSet.newlines).filter { !$0.isEmpty }
var grid = [D4 : Bool]()
//var grid = [D3 : Bool]() // for 3D simulation
for (x,line) in lines.enumerated() {
for (y, char) in line.enumerated() {
grid[D4(x,y,0,0)] = char == "#"
// grid[D3(x,y,0,0)] = char == "#" // for 3D simulation
}
}
var newGrid = grid
for _ in 0..<6 {
grid = newGrid
for element in grid {
let coordinate = element.key
for neighbor in coordinate.neighbors {
if grid[neighbor] == nil {
grid[neighbor] = false
}
}
}
for element in grid {
let coordinate = element.key
var activeNeighbors = 0
for neighbor in coordinate.neighbors {
if grid[neighbor] == true {
activeNeighbors += 1
} else {
if newGrid[neighbor] == nil {
newGrid[neighbor] = false
}
}
}
if grid[coordinate] == true {
if activeNeighbors == 2 || activeNeighbors == 3 {
newGrid[coordinate] = true
} else {
newGrid[coordinate] = false
}
} else {
if activeNeighbors == 3 {
newGrid[coordinate] = true
} else {
newGrid[coordinate] = false
}
}
}
}
print(newGrid.filter { $0.value }.count)
struct D3 : Hashable {
let x: Int
let y: Int
let z: Int
init(_ x: Int, _ y: Int, _ z: Int) {
self.x = x
self.y = y
self.z = z
}
var neighbors: [D3] {
return [
D3(x+1,y,z),
D3(x+1,y,z+1),
D3(x+1,y,z-1),
D3(x+1,y+1,z+1),
D3(x+1,y+1,z-1),
D3(x+1,y+1,z),
D3(x+1,y-1,z+1),
D3(x+1,y-1,z-1),
D3(x+1,y-1,z),
D3(x,y,z+1),
D3(x,y,z-1),
D3(x,y+1,z+1),
D3(x,y+1,z-1),
D3(x,y+1,z),
D3(x,y-1,z+1),
D3(x,y-1,z-1),
D3(x,y-1,z),
D3(x-1,y,z),
D3(x-1,y,z+1),
D3(x-1,y,z-1),
D3(x-1,y+1,z+1),
D3(x-1,y+1,z-1),
D3(x-1,y+1,z),
D3(x-1,y-1,z+1),
D3(x-1,y-1,z-1),
D3(x-1,y-1,z),
]
}
}
struct D4 : Hashable {
let x: Int
let y: Int
let z: Int
let w: Int
init(_ x: Int, _ y: Int, _ z: Int, _ w: Int) {
self.x = x
self.y = y
self.z = z
self.w = w
}
init(c: D3, _ w: Int) {
self.x = c.x
self.y = c.y
self.z = c.z
self.w = w
}
var neighbors: [D4] {
return [D4(x, y, z, w-1), D4(x, y, z, w+1)] + D3(x,y,z).neighbors.flatMap { [D4($0.x,$0.y,$0.z,w), D4($0.x,$0.y,$0.z,w+1), D4($0.x,$0.y,$0.z,w-1)] }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment