Created
December 24, 2020 07:50
-
-
Save felix-larsen/226facf68b538ec05a8d731606bd27f3 to your computer and use it in GitHub Desktop.
24th December solution - Advent of Code 2020 - swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let occurences = coordinates.reduce(into: [:]) { counts, coordinate in counts[coordinate, default: 0] += 1 } | |
print(occurences.filter { $0.value % 2 == 1 }.count) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var grid = Dictionary(uniqueKeysWithValues:occurences.map { ($0.key,$0.value % 2 == 1) }.filter { $0.1 }) | |
var newGrid = grid | |
for _ in 0..<100 { | |
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 == 0 || activeNeighbors > 2 { | |
newGrid[coordinate] = false | |
} else { | |
newGrid[coordinate] = true | |
} | |
} else { | |
if activeNeighbors == 2 { | |
newGrid[coordinate] = true | |
} else { | |
newGrid[coordinate] = false | |
} | |
} | |
} | |
} | |
print(newGrid.filter { $0.value }.count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment