Rework a bit to avoid manually counting double newlines.

Also store the hashmap directly in the arraylist, although no idea
how the memory management works.
This commit is contained in:
Adam Millerchip 2022-08-14 18:14:49 +09:00
parent fc0eb4a63c
commit 1f7c32b758

View file

@ -12,33 +12,28 @@ const gpa = util.gpa;
const input = @embedFile("input"); const input = @embedFile("input");
pub fn main() !void { pub fn main() !void {
// *still* don't know how to manage the memory here... var line_it = split(u8, input, "\n");
var passports = ArrayList([]const u8).init(gpa); var passports = ArrayList(StringHashMap([]const u8)).init(gpa);
var building_passport = ArrayList(u8).init(gpa); var fields = StringHashMap([]const u8).init(gpa);
var prev: u8 = 'a'; while (line_it.next()) |line| {
// Ugh. How do we split on a known string (not single byte)? if (line.len == 0) {
for (input) |char| { try passports.append(try fields.clone());
if (prev == '\n' and char == '\n') { fields.clearAndFree();
try passports.append(building_passport.toOwnedSlice());
} else { } else {
try building_passport.append(char); var token_it = tokenize(u8, line, " :");
prev = char; while (token_it.next()) |token| {
try fields.put(token, token_it.next().?);
} }
} }
try passports.append(building_passport.toOwnedSlice()); }
try passports.append(fields);
const required_fields = [_][]const u8{ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" }; const required_fields = [_][]const u8{ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" };
var valid_count: usize = 0; var valid_count: usize = 0;
for (passports.items) |passport| { for (passports.items) |passport| {
var tokens = tokenize(u8, passport, ": \n"); var valid: bool = true;
var fields = StringHashMap(u8).init(gpa);
while (tokens.next()) |token| {
try fields.put(token, 1);
_ = tokens.next();
}
var valid = true;
for (required_fields) |required_field| { for (required_fields) |required_field| {
valid = valid and fields.contains(required_field); valid = valid and passport.contains(required_field);
} }
if (valid) valid_count += 1; if (valid) valid_count += 1;
} }