Compare commits

..

No commits in common. "59157c5a116979ee47a5f7a75a1a15e057c92c7d" and "6d677300ee3adf460fa483816b042297df7e6033" have entirely different histories.

View file

@ -1,60 +1,44 @@
const std = @import("std"); const std = @import("std");
const gpa = @import("util.zig").gpa; const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList; const List = std.ArrayList;
const tokenize = std.mem.tokenize; const Map = std.AutoHashMap;
const parseInt = std.fmt.parseInt; const StrMap = std.StringHashMap;
const print = std.debug.print; const BitSet = std.DynamicBitSet;
const Str = []const u8;
const data = @embedFile("input"); const util = @import("util.zig");
const gpa = util.gpa;
const Rule = struct { const data = @embedFile("../data/day02.txt");
a: u8, b: u8, char: u8, password: []const u8
};
pub fn main() !void { pub fn main() !void {
const rules = try parse();
print("Part 1: {d}\n", .{part1(rules)});
print("Part 2: {d}\n", .{part2(rules)});
} }
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
fn parse() ![]Rule { const parseInt = std.fmt.parseInt;
var it = tokenize(u8, data, "\n"); const parseFloat = std.fmt.parseFloat;
var rules = ArrayList(Rule).init(gpa);
while (it.next()) |line| {
var line_it = tokenize(u8, line, ": -");
const a = try parseInt(u8, line_it.next().?, 10);
const b = try parseInt(u8, line_it.next().?, 10);
const char = line_it.next().?[0];
const password = line_it.next().?;
try rules.append(Rule{.a = a, .b = b, .char = char, .password = password});
}
return rules.toOwnedSlice();
}
fn part1(rules: []Rule) !u16 { const min = std.math.min;
var valid_pw_count: u16 = 0; const min3 = std.math.min3;
for (rules) |rule| { const max = std.math.max;
var count: u8 = 0; const max3 = std.math.max3;
for (rule.password) |password_char| {
if (rule.char == password_char)
count += 1;
}
if (rule.a <= count and count <= rule.b) const print = std.debug.print;
valid_pw_count += 1; const assert = std.debug.assert;
}
return valid_pw_count;
}
fn part2(rules: []Rule) !u16 { const sort = std.sort.sort;
var valid_pw_count: u16 = 0; const asc = std.sort.asc;
for (rules) |rule| { const desc = std.sort.desc;
const a_match = rule.password[rule.a-1] == rule.char;
const b_match = rule.password[rule.b-1] == rule.char;
// No xor in zig?
if (a_match and !b_match or !a_match and b_match)
valid_pw_count += 1;
}
return valid_pw_count;
}