unwashed day07
This commit is contained in:
parent
05ffa1e7c1
commit
221cad1136
@ -4,7 +4,7 @@ const mem = std.mem;
|
||||
|
||||
pub fn main() !void {
|
||||
const input = @embedFile("data/day07.txt");
|
||||
const sln = try solve(util.gpa, input);
|
||||
const sln = try solve2(util.gpa, input);
|
||||
std.debug.print("{d}\n", .{sln.a});
|
||||
std.debug.print("{d}\n", .{sln.b});
|
||||
}
|
||||
@ -38,9 +38,9 @@ fn fixCards(cards: *[5]u8) void {
|
||||
'A' => 13,
|
||||
'K' => 12,
|
||||
'Q' => 11,
|
||||
'J' => 10,
|
||||
'J' => 0,
|
||||
'T' => 9,
|
||||
'2'...'9' => card - '2',
|
||||
'2'...'9' => card - '1',
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
@ -67,6 +67,29 @@ fn scoreHand(cards: Cards) Score {
|
||||
};
|
||||
}
|
||||
|
||||
const joker = 0;
|
||||
|
||||
fn scoreHand2(cards: Cards) Score {
|
||||
var jokers: usize = 0;
|
||||
var dups: [14]u8 = undefined;
|
||||
@memset(&dups, 0);
|
||||
for (cards) |a| {
|
||||
if (a == joker) {
|
||||
jokers += 1;
|
||||
} else {
|
||||
dups[a] += 1;
|
||||
}
|
||||
}
|
||||
std.mem.sort(u8, &dups, {}, u8gt);
|
||||
return switch (dups[0] + jokers) {
|
||||
5 => .fiveKind,
|
||||
4 => .fourKind,
|
||||
3 => if (dups[1] == 2) .fullHouse else .threeKind,
|
||||
2 => if (dups[1] == 2) .twoPair else .onePair,
|
||||
else => .high,
|
||||
};
|
||||
}
|
||||
|
||||
fn compareHand(context: void, a: Hand, b: Hand) bool {
|
||||
_ = context;
|
||||
if (a.score != b.score) {
|
||||
@ -111,6 +134,34 @@ fn solve(alloc: mem.Allocator, input: []const u8) !Solution {
|
||||
return .{ .a = partA, .b = 0 };
|
||||
}
|
||||
|
||||
fn solve2(alloc: mem.Allocator, input: []const u8) !Solution {
|
||||
var hands = try std.ArrayList(Hand).initCapacity(alloc, 1001);
|
||||
defer hands.deinit();
|
||||
|
||||
var it = util.splitLines(input);
|
||||
while (it.next()) |line| {
|
||||
if (line.len == 0) continue;
|
||||
|
||||
var cards = line[0..5].*;
|
||||
fixCards(&cards);
|
||||
const bid = try std.fmt.parseInt(u32, line[6..], 10);
|
||||
const score = scoreHand2(cards);
|
||||
const hand = Hand{ .cards = cards, .bid = bid, .score = score };
|
||||
try hands.append(hand);
|
||||
}
|
||||
|
||||
// std.debug.print("{any}\n", .{hands.items});
|
||||
try sortHands(&hands);
|
||||
|
||||
var partB: usize = 0;
|
||||
for (hands.items, 1..) |hand, rank| {
|
||||
// std.debug.print("{d} * {d}\n", .{ hand.bid, rank });
|
||||
partB += hand.bid * rank;
|
||||
}
|
||||
|
||||
return .{ .a = 0, .b = partB };
|
||||
}
|
||||
|
||||
test "silver" {
|
||||
const input =
|
||||
\\32T3K 765
|
||||
@ -131,6 +182,6 @@ test "gold" {
|
||||
\\KTJJT 220
|
||||
\\QQQJA 483
|
||||
;
|
||||
const sln = try solve(std.testing.allocator, input);
|
||||
try std.testing.expectEqual(@as(usize, 0), sln.b);
|
||||
const sln = try solve2(std.testing.allocator, input);
|
||||
try std.testing.expectEqual(@as(usize, 5905), sln.b);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user