Day 13. still haven't finished day 12. Today was so easy compared to

yesterday.
master
Dustin Swan 1 year ago
parent 90a32e4439
commit 68f1500953
Signed by: dustinswan
GPG Key ID: AB49BD6B2B3A6377

@ -0,0 +1,119 @@
const std = @import("std");
pub fn main() !void {
const content = @embedFile("data.txt");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
// yo dog
var grids = std.ArrayList(std.ArrayList(std.ArrayList(u8))).init(allocator);
var sections = std.mem.split(u8, content, "\n\n");
while (sections.next()) |section| {
var lines = std.mem.split(u8, section, "\n");
var gridArrayList = std.ArrayList(std.ArrayList(u8)).init(allocator);
while (lines.next()) |line| {
if (line.len < 1) {
break;
}
var lineArrayList = std.ArrayList(u8).init(allocator);
for (line) |char| {
try lineArrayList.append(char);
}
try gridArrayList.append(lineArrayList);
}
try grids.append(gridArrayList);
}
var part1: usize = 0;
var part2: usize = 0;
for (grids.items) |grid| {
const transposed = try transpose(grid, allocator);
const rowReflection = findRowReflection(grid);
const columnReflection = findRowReflection(transposed);
part1 += 100 * (rowReflection orelse 0) + (columnReflection orelse 0);
const rowSmudge = findSmudge(grid);
const colSmudge = findSmudge(transposed);
part2 += 100 * (rowSmudge orelse 0) + (colSmudge orelse 0);
}
std.debug.print("part1 {d}\n", .{part1});
std.debug.print("part2 {d}\n", .{part2});
}
fn findSmudge(grid: std.ArrayList(std.ArrayList(u8))) ?usize {
const height = grid.items.len;
for (1..height) |row| {
var numDiff: u8 = 0;
for (1..row + 1) |d| {
const row1 = grid.items[row - d];
const row2 = grid.items[row + d - 1];
for (0..row1.items.len) |i| {
if (row1.items[i] != row2.items[i]) {
numDiff += 1;
}
}
if (numDiff > 1) {
break;
}
if (row - d == 0 or row + d == height) {
break;
}
}
if (numDiff == 1) {
return row;
}
}
return null;
}
fn findRowReflection(grid: std.ArrayList(std.ArrayList(u8))) ?usize {
const height = grid.items.len;
for (1..height) |row| {
for (1..row + 1) |d| {
const row1 = grid.items[row - d];
const row2 = grid.items[row + d - 1];
if (!std.mem.eql(u8, row1.items, row2.items)) {
break;
}
if (row - d == 0 or row + d == height) {
return row;
}
}
}
return null;
}
fn transpose(grid: std.ArrayList(std.ArrayList(u8)), allocator: std.mem.Allocator) !std.ArrayList(std.ArrayList(u8)) {
const height = grid.items.len;
const width = grid.items[0].items.len;
var grid2 = std.ArrayList(std.ArrayList(u8)).init(allocator);
for (0..width) |c| {
var row = std.ArrayList(u8).init(allocator);
for (0..height) |r| {
try row.append(grid.items[r].items[c]);
}
try grid2.append(row);
}
return grid2;
}
Loading…
Cancel
Save