Day 3 improvement
Closed this issue · 2 comments
mpcjanssen commented
As a fellow AoC solver I looked at the day3 solution to see how fast nim was compared to my solution in Tcl. Surprisingly it was much slower (my Tcl solution takes less than a second).
Turns out the calculation of the intersections is very slow because of the algorithm it uses. Just as a FYI the adapted code below calculates the results within 80ms on my system.
import strutils
import sequtils
import math
import sugar
import algorithm
import sets
from sequtils import map
import algorithm
proc readWires(): (seq[string], seq[string]) =
let file = open("input.txt")
let wire1Raw = readLine(file)
let wire1 = wire1Raw.strip().split(",")
let wire2Raw = readLine(file)
let wire2 = wire2Raw.strip().split(",")
return (wire1, wire2)
let (wire1, wire2) = readWires()
proc computePath(instructions: seq[string]): seq[(int, int)] =
var coord = (0, 0) # x, y, step
var path: seq[(int, int)]
for inst in instructions:
let direction = inst[0]
let numStep = inst[1..^1].parseInt
var dx = 0
var dy = 0
case direction
of 'D':
dy = 1
of 'L':
dx = -1
of 'R':
dx = 1
of 'U':
dy = -1
else:
echo "Fatal"
for i in 1..numStep:
coord[0] += dx
coord[1] += dy
path.add(coord)
return path
let path1 = computePath(wire1)
let path2 = computePath(wire2)
let intersections = toHashSet(path1).intersection(toHashSet(path2)).toSeq
var steps = intersections.map(x => (path1.find(x) + path2.find(x), x))
steps.sort( proc (x,y: (int,(int,int))): int =
cmp(x[0], y[0] ))
echo steps[0]
var manhattan = intersections.map(x => (abs(x[0]) + abs(x[1]),x))
manhattan.sort( proc (x,y: (int,(int,int))): int =
cmp(x[0], y[0] ))
echo manhattan[0]
Coac commented
Yes my implementation is not very smart
Thank you for your version, it's way faster 👍
mpcjanssen commented
Lesson I keep relearning myself. Use the stdlib :-)