const std = @import("std");
const PATH = "input/day22.txt";
const Str = []const u8;
pub fn first(allocator: ?std.mem.Allocator) anyerror!usize {
var game = try parseInput(allocator.?, @embedFile(PATH));
defer {
game.p1.deinit();
game.p2.deinit();
}
try game.play();
var sum: usize = 0;
for (game.p1.items) |item, idx| {
sum += (game.p1.items.len - idx) * item;
}
for (game.p2.items) |item, idx| {
sum += (game.p2.items.len - idx) * item;
}
return sum;
}
pub fn second(allocator: ?std.mem.Allocator) anyerror!usize {
_ = allocator;
return 0;
}
const CardType = u6;
const Game = struct {
round: usize = 0,
p1: std.ArrayList(CardType),
p2: std.ArrayList(CardType),
fn play(self: *@This()) anyerror!void {
if (self.p1.items.len == 0 or self.p2.items.len == 0) {
return;
}
self.round += 1;
const p1 = self.p1.orderedRemove(0);
const p2 = self.p2.orderedRemove(0);
if (p1 > p2) {
try self.p1.append(p1);
try self.p1.append(p2);
} else {
try self.p2.append(p2);
try self.p2.append(p1);
}
try self.play();
}
};
fn parseInput(allocator: std.mem.Allocator, input: Str) !Game {
var ret = Game{
.p1 = std.ArrayList(CardType).init(allocator),
.p2 = std.ArrayList(CardType).init(allocator),
};
var lines = std.mem.split(u8, input, "\n");
// Player 1
while (lines.next()) |line| {
if (line.len == 0) break;
if (line[0] == 'P') continue;
const num = try std.fmt.parseUnsigned(CardType, line, 10);
try ret.p1.append(num);
}
// Player 2
while (lines.next()) |line| {
if (line.len == 0) break;
if (line[0] == 'P') continue;
const num = try std.fmt.parseUnsigned(CardType, line, 10);
try ret.p2.append(num);
}
return ret;
}
test "day21a" {
try std.testing.expectEqual(@as(usize, 33561), try first(std.testing.allocator));
}
test "day21b" {
try std.testing.expectEqual(@as(usize, 0), try second(std.testing.allocator));
}
const test_input =
\\Player 1:
\\9
\\2
\\6
\\3
\\1
\\
\\Player 2:
\\5
\\8
\\4
\\7
\\10
;