#import "Basic";
#import "String";
#import "File";
#import "Math";
solve_day18 :: (test: bool) {
contents := read_entire_file(ifx test then "inputs/day18_test.txt" else "inputs/day18.txt");
lines := split(contents, "\n");
part1 := 0;
part2 := 0;
position: Coord;
position_2: Coord;
polygon: [..]Coord;
polygon_2: [..]Coord;
for line: lines {
index_after_amount := find_index_from_left(slice(line, 2, line.count - 2), #char " ");
index_of_hashtag := find_index_from_left(line, #char "#");
amount := string_to_int(slice(line, 2, index_after_amount), 10, s32);
amount_2 := string_to_int(slice(line, index_of_hashtag + 1, 5), 16, s32);
part1 += amount;
part2 += amount_2;
dir := convert_to_coord(line[0]);
dir_convert := u8.[#char "R", #char "D", #char "L", #char "U"];
dir_2 := convert_to_coord(dir_convert[line[index_of_hashtag + 6] - #char "0"]);
position.x += dir.x * amount;
position.y += dir.y * amount;
position_2.x += dir_2.x * amount_2;
position_2.y += dir_2.y * amount_2;
array_add(*polygon, position);
array_add(*polygon_2, position_2);
}
print("Part 1: %\n", shoelace_area(polygon) + xx (part1 / 2 + 1));
print("Part 2: %\n", shoelace_area(polygon_2) + xx (part2 / 2 + 1));
}
convert_to_coord :: (dir: u8) -> Coord {
if dir == {
case #char "U";
return .{ x = 0, y = 1 };
case #char "D";
return .{ x = 0, y = -1 };
case #char "L";
return .{ x = -1, y = 0 };
case #char "R";
return .{ x = 1, y = 0 };
case;
return .{ x = 0, y = 0 };
}
}
shoelace_area :: (polygon: [..]Coord) -> s64 {
area := 0;
for 0..polygon.count - 1 {
p1 := polygon[it];
p2 := polygon[((it + 1) % polygon.count)];
area += p1.x * p2.y - p2.x * p1.y;
}
return abs(area) / 2;
}
#scope_file
Coord :: struct {
x: s64 = 0;
y: s64 = 0;
}