AdventOfCode/2020/zig/src/day02.zig

63 lines
1.7 KiB
Zig
Raw Normal View History

2022-08-11 07:34:17 +00:00
const std = @import("std");
2022-08-11 15:22:15 +00:00
const gpa = @import("util.zig").gpa;
2022-08-11 15:32:02 +00:00
const Allocator = std.mem.Allocator;
2022-08-11 15:22:15 +00:00
const ArrayList = std.ArrayList;
const tokenize = std.mem.tokenize;
const parseInt = std.fmt.parseInt;
const print = std.debug.print;
2022-08-11 07:34:17 +00:00
2022-08-11 14:30:52 +00:00
const data = @embedFile("input");
2022-08-11 07:34:17 +00:00
2022-08-11 15:22:15 +00:00
const Rule = struct {
a: u8, b: u8, char: u8, password: []const u8
};
2022-08-11 07:34:17 +00:00
pub fn main() !void {
2022-08-11 15:22:15 +00:00
const rules = try parse();
2022-08-11 15:32:02 +00:00
defer Allocator.free(gpa, rules);
2022-08-11 15:22:15 +00:00
print("Part 1: {d}\n", .{part1(rules)});
print("Part 2: {d}\n", .{part2(rules)});
2022-08-11 14:53:24 +00:00
}
2022-08-11 15:22:15 +00:00
fn parse() ![]Rule {
2022-08-11 14:30:52 +00:00
var it = tokenize(u8, data, "\n");
2022-08-11 15:22:15 +00:00
var rules = ArrayList(Rule).init(gpa);
2022-08-11 14:30:52 +00:00
while (it.next()) |line| {
var line_it = tokenize(u8, line, ": -");
2022-08-11 15:22:15 +00:00
const a = try parseInt(u8, line_it.next().?, 10);
const b = try parseInt(u8, line_it.next().?, 10);
const char = line_it.next().?[0];
2022-08-11 14:30:52 +00:00
const password = line_it.next().?;
2022-08-11 15:22:15 +00:00
try rules.append(Rule{.a = a, .b = b, .char = char, .password = password});
}
return rules.toOwnedSlice();
}
2022-08-11 14:30:52 +00:00
2022-08-11 16:31:10 +00:00
fn part1(rules: []Rule) u16 {
2022-08-11 15:22:15 +00:00
var valid_pw_count: u16 = 0;
for (rules) |rule| {
2022-08-11 14:30:52 +00:00
var count: u8 = 0;
2022-08-11 15:22:15 +00:00
for (rule.password) |password_char| {
if (rule.char == password_char)
2022-08-11 14:30:52 +00:00
count += 1;
}
2022-08-11 15:22:15 +00:00
if (rule.a <= count and count <= rule.b)
2022-08-11 14:30:52 +00:00
valid_pw_count += 1;
2022-08-11 14:53:24 +00:00
}
return valid_pw_count;
}
2022-08-11 16:31:10 +00:00
fn part2(rules: []Rule) u16 {
2022-08-11 14:53:24 +00:00
var valid_pw_count: u16 = 0;
2022-08-11 15:22:15 +00:00
for (rules) |rule| {
const a_match = rule.password[rule.a-1] == rule.char;
const b_match = rule.password[rule.b-1] == rule.char;
2022-08-11 14:53:24 +00:00
// No xor in zig?
if (a_match and !b_match or !a_match and b_match)
valid_pw_count += 1;
2022-08-11 14:30:52 +00:00
}
2022-08-11 14:53:24 +00:00
return valid_pw_count;
2022-08-11 07:34:17 +00:00
}