Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 12, 2020 10:28
Show Gist options
  • Save felix-larsen/1880d42aeb86e254706af943717d2840 to your computer and use it in GitHub Desktop.
Save felix-larsen/1880d42aeb86e254706af943717d2840 to your computer and use it in GitHub Desktop.
12th December solution - Advent of Code 2020 - swift
var x = 0.0
var y = 0.0
var direction = 0.0 // degrees east
lines.forEach { (line) in
if let instruction = line.first, let amount = Double(line.dropFirst()) {
if instruction == "E" {
x += amount
} else if instruction == "W" {
x -= amount
} else if instruction == "N" {
y -= amount
} else if instruction == "S" {
y += amount
} else if instruction == "F" {
x += amount * __cospi(direction/180.0)
y += amount * __sinpi(direction/180.0)
} else if instruction == "R" {
direction += amount
} else if instruction == "L" {
direction -= amount
}
}
}
print(abs(x) + abs(y))
var waypointX = 10.0
var waypointY = -1.0
var x = 0.0
var y = 0.0
lines.forEach { (line) in
if let instruction = line.first, let amount = Double(line.dropFirst()) {
if instruction == "E" {
waypointX += amount
} else if instruction == "W" {
waypointX -= amount
} else if instruction == "N" {
waypointY -= amount
} else if instruction == "S" {
waypointY += amount
} else if instruction == "F" {
x += amount * waypointX
y += amount * waypointY
} else if instruction == "R" {
for _ in 0 ..< Int(amount/90) {
let oldX = waypointX
let oldY = waypointY
waypointX = oldY * -1
waypointY = oldX
}
} else if instruction == "L" {
for _ in 0 ..< Int(amount/90) {
let oldX = waypointX
let oldY = waypointY
waypointX = oldY
waypointY = oldX * -1
}
}
}
}
print(abs(x) + abs(y))
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december12.txt"
let contents = try! String(contentsOfFile: filename)
var lines = contents.components(separatedBy: CharacterSet.newlines).filter { !$0.isEmpty }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment