Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 3, 2020 07:40
Show Gist options
  • Save felix-larsen/2f2db141e4c7d3100be40f1774cad4ba to your computer and use it in GitHub Desktop.
Save felix-larsen/2f2db141e4c7d3100be40f1774cad4ba to your computer and use it in GitHub Desktop.
3rd December solution - Advent of Code 2020 - swift
let treeCount = countTrees(in: lines, dX: 3, dY: 1)
print(treeCount)
var treeCounts = [Int]()
treeCounts.append(countTrees(in: lines, dX: 1, dY: 1))
treeCounts.append(countTrees(in: lines, dX: 3, dY: 1))
treeCounts.append(countTrees(in: lines, dX: 5, dY: 1))
treeCounts.append(countTrees(in: lines, dX: 7, dY: 1))
treeCounts.append(countTrees(in: lines, dX: 1, dY: 2))
print(treeCounts.reduce(1, *))
func countTrees(in lines: [String.SubSequence], dX: Int, dY: Int) -> Int {
var x = 0
var treeCount = 0
for lineIndex in stride(from: 0, to: lines.count - 1, by: dY) {
let line = String(lines[lineIndex])
if line.charAt(x % line.count) == "#"
{
treeCount += 1
}
x += dX
}
return treeCount
}
extension String {
func charAt(_ i: Int) -> Character {
return Array(self)[i]
}
}
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december03.txt"
let contents = try! String(contentsOfFile: filename)
let lines = contents.split(separator:"\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment