This commit is contained in:
2019-12-03 23:45:30 +00:00
parent 67f3c61d57
commit fd875fe36b

View File

@@ -5,6 +5,7 @@ const Error = error{ParseError};
const Point = struct {
X: i32,
Y: i32,
Steps: i32, // number of steps taken to reach this point
};
const Points = std.ArrayList(Point);
@@ -44,48 +45,52 @@ const Step = struct {
const World = struct {
entries: Points,
pos: Point,
ticks: i32,
x: i32,
y: i32,
pub fn step(self: *World, in: Step) anyerror!void {
std.debug.warn("Step: {}\n", in);
pub fn step(self: *World, in: Step) void {
std.debug.warn("Step {}: {}\n", self.ticks, in);
var i: i32 = 0;
switch (in.d) {
.Up => {
try self.lineY(self.pos.Y - in.l, self.pos.Y - 1);
self.pos.Y -= in.l;
while (i < in.l) : (i += 1) {
self.y -= 1;
self.fill();
}
},
.Down => {
try self.lineY(self.pos.Y + 1, self.pos.Y + in.l);
self.pos.Y += in.l;
while (i < in.l) : (i += 1) {
self.y += 1;
self.fill();
}
},
.Left => {
try self.lineX(self.pos.X - in.l, self.pos.X - 1);
self.pos.X -= in.l;
while (i < in.l) : (i += 1) {
self.x -= 1;
self.fill();
}
},
.Right => {
try self.lineX(self.pos.X + 1, self.pos.X + in.l);
self.pos.X += in.l;
while (i < in.l) : (i += 1) {
self.x += 1;
self.fill();
}
},
}
}
fn lineX(self: *World, start: i32, end: i32) anyerror!void {
var x: i32 = start;
while (x <= end) : (x += 1) {
try self.fill(x, self.pos.Y);
}
}
fn fill(self: *World) void {
self.ticks += 1;
fn lineY(self: *World, start: i32, end: i32) anyerror!void {
var y: i32 = start;
while (y <= end) : (y += 1) {
try self.fill(self.pos.X, y);
}
}
const point = Point{ .X = self.x, .Y = self.y, .Steps = self.ticks };
fn fill(self: *World, x: i32, y: i32) anyerror!void {
//self.entries = try self.alloc.realloc(self.entries, self.entries.len+1);
self.entries.appendAssumeCapacity(Point{ .X = x, .Y = y });
// TODO: use the lower number of ticks for multiple crossings
// I'm lucky, I don't need this.
std.debug.warn("\t{}\n", point);
self.entries.appendAssumeCapacity(point);
}
};
@@ -123,22 +128,26 @@ pub fn main() anyerror!void {
var world: World = World{
.entries = try Points.initCapacity(alloc, maxEntries),
.pos = Point{ .X = 0, .Y = 0 },
.ticks = 0,
.x = 0,
.y = 0,
};
// Line 1
for (try getLine(stream)) |item| {
try world.step(item);
world.step(item);
}
// reset to origin
const entriesA = world.entries;
world.entries = try Points.initCapacity(alloc, maxEntries);
world.pos = Point{ .X = 0, .Y = 0 };
world.ticks = 0;
world.x = 0;
world.y = 0;
// Line 2
for (try getLine(stream)) |item| {
try world.step(item);
world.step(item);
}
const entriesB = world.entries;
@@ -148,7 +157,7 @@ pub fn main() anyerror!void {
for (entriesA.toSlice()) |a| {
for (entriesB.toSlice()) |b| {
if (a.X == b.X and a.Y == b.Y) {
std.debug.warn("Match! {} => {}\n", a, manhattan(a.X, a.Y));
std.debug.warn("Match! {}, {} => {} : {}\n", a, b, manhattan(a.X, a.Y), a.Steps + b.Steps);
}
}
}