Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package aoc;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.TreeSet;
import java.util.function.Consumer;
public class Aoc3 {
public static class Point implements Comparable<Point>
{
final int x;
final int y;
final int dist;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
this.dist = Math.abs(x)+Math.abs(y);
}
@Override
public int compareTo(Point o) {
int n = Integer.compare(this.dist, o.dist);
if( n == 0) n = Integer.compare(this.x, o.x);
if( n == 0) n = Integer.compare(this.y, o.y);
return n;
}
@Override
public boolean equals(Object obj) {
Point o = (Point) obj;
return (o.x == this.x) && (o.y == this.y);
}
@Override
public String toString() {
return "x=" + x + ", y=" + y;
}
}
private static void listPoints(String line, Consumer<Point> c)
{
int x = 0;
int y = 0;
for (String step : line.split(",")) {
char dir = step.charAt(0);
int length = Integer.parseInt(step.substring(1));
for (int i = 0; i < length; i++) {
switch (dir) {
case 'R': x++;break;
case 'L': x--;break;
case 'U': y++;break;
case 'D': y--;break;
}
c.accept(new Point(x,y));
}
}
}
static Point best = null;
public static void main(String[] args) throws IOException {
var lines = Files.readAllLines(Paths.get("c:\\nicola\\input.txt"));
System.out.println(new Date());
var points1 = new TreeSet<Point>();
listPoints(lines.get(0), points1::add);
listPoints(lines.get(1), p -> {
if(points1.contains(p))
{
if (best == null || (best.dist > p.dist)) {
best = p;
}
}
});
System.out.println("Best is: "+best+" dist: "+best.dist);
System.out.println(new Date());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.