Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 20, 2020 07:32
Show Gist options
  • Save felix-larsen/8590493046f58cab90c5aa8d472ad075 to your computer and use it in GitHub Desktop.
Save felix-larsen/8590493046f58cab90c5aa8d472ad075 to your computer and use it in GitHub Desktop.
20th December solution - Advent Of Code 2020 - swift
import Foundation
struct Tile {
let id: Int
let imageData: [String]
var borders: [String] {
var list = [String]()
list.append(imageData.first!)
list.append(String(imageData.last!))
list.append(String(imageData.map { $0.first! }))
list.append(String(imageData.map { $0.last! }))
return list
}
var flippedVert: Tile {
return Tile(id: self.id, imageData: imageData.reversed() as [String])
}
var flippedHorz: Tile {
return Tile(id: self.id, imageData: imageData.map { String($0.reversed()) })
}
var allPossibleBorders: [String] {
var list = [String]()
list.append(contentsOf: borders)
list.append(contentsOf: borders.map{String($0.reversed())})
return list
}
}
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december20.txt"
let contents = try! String(contentsOfFile: filename)
let lines = contents.components(separatedBy: CharacterSet.newlines).filter { !$0.isEmpty}
var tiles = [Tile]()
var currentTileId = -1
var currentImageData = [String]()
for line in lines {
if line.contains("Tile") {
if currentTileId != -1 {
tiles.append(Tile(id: currentTileId, imageData: currentImageData))
}
currentTileId = Int(line.components(separatedBy: "Tile ")[1].dropLast())!
currentImageData = [String]()
} else {
currentImageData.append(line)
}
}
tiles.append(Tile(id: currentTileId, imageData: currentImageData))
print(tiles.count)
var cornerTiles = [Tile]()
var i = 0
while i < tiles.count {
let tile = tiles[i]
if countBordersMatched(tile) == 2 {
cornerTiles.append(tile)
}
i += 1
}
print(cornerTiles.count)
print(cornerTiles.map { $0.id }.reduce(1, *))
func countBordersMatched(_ tile: Tile) -> Int {
var matchingBorders = 0
borders: for border in tile.borders {
for j in 0..<tiles.count {
let cTile = tiles[j]
if cTile.id != tile.id {
if cTile.allPossibleBorders.contains(border) {
matchingBorders += 1
continue borders
}
}
}
}
return matchingBorders
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment