### re: Advent of Code 2019 Solution Megathread - Day 12: The N-Body Problem VIEW POST

Quick and dirty part one in swift. Need more time for part 2.

``````import Cocoa

let input = """
<x=17, y=5, z=1>
<x=-2, y=-8, z=8>
<x=7, y=-6, z=14>
<x=1, y=-10, z=4>
""".components(separatedBy: "\n")

let pattern = "<x=(.+), y=(.+), z=(.+)>"
let regex = try? NSRegularExpression(pattern: pattern, options: [])

var vectors = input.map { line -> [Int] in
if let match = regex?.firstMatch(in: line, options: [], range: NSRange.init(location: 0, length: line.utf8.count)) {
if let x = Range(match.range(at: 1), in: line),
let y = Range(match.range(at: 2), in: line),
let z = Range(match.range(at: 3), in: line) {
return [Int(line[x])!, Int(line[y])!, Int(line[z])!]
}
}
return []
}

print(vectors)

func partOne() -> Int {
var vel: [[Int]] = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
for _ in 0 ... 999 {
for i in 0 ... vectors.count - 1 {
for j in 0 ... vectors.count - 1  {
for k in 0 ... vectors[i].count - 1 {
//print("\(i) \(j) \(k)")
if vectors[i][k] < vectors[j][k] {
vel[i][k] += 1
}
else if vectors[i][k] > vectors[j][k] {
vel[i][k] -= 1
}
}
}
}
for i in 0 ... vectors.count - 1 {
for k in 0 ... vectors[i].count - 1 {
vectors[i][k] += vel[i][k]
}
}
}

var p1 = 0
for i in 0 ... vectors.count - 1  {
var pot = 0
var kin = 0
for k in 0 ... vectors[i].count - 1 {
pot += abs(vectors[i][k])
kin += abs(vel[i][k])
}
p1 += pot*kin
}

print(vectors)
print(vel)
print(p1)
return p1
}

print(partOne())

``````

Forgot to post day 12 part two solution - It Took long time and don't know any leads so I checked the hit from r site and it was easy ride from that.

Swift code can be found here github.com/rizwankce/AdventOfCode/...

code of conduct - report abuse