Skip to content

Instantly share code, notes, and snippets.

@akhildevelops
Created November 10, 2025 02:08
Show Gist options
  • Select an option

  • Save akhildevelops/fc3f1597b7f9b35f6959c2b55cef3ecf to your computer and use it in GitHub Desktop.

Select an option

Save akhildevelops/fc3f1597b7f9b35f6959c2b55cef3ecf to your computer and use it in GitHub Desktop.
day3.zig
const std = @import("std");
fn part1(buffer: []const u8, allocator: std.mem.Allocator) !void {
var n_iterator = std.mem.splitScalar(u8, buffer, ',');
var hashset = std.AutoHashMap(u32, void).init(allocator);
defer hashset.deinit();
var total: u32 = 0;
while (n_iterator.next()) |size| {
const _size = try std.fmt.parseInt(u32, size, 10);
if (hashset.get(_size)) |_| continue;
try hashset.put(_size, {});
total += _size;
}
std.debug.print("{d}\n", .{total});
}
fn parse_to_u16(buffer: []const u8, allocator: std.mem.Allocator) ![]const u16 {
var numbers = std.ArrayList(u16){};
var num_iter = std.mem.splitScalar(u8, buffer, ',');
var index: usize = 0;
while (num_iter.next()) |num| : (index += 1) {
const number = try std.fmt.parseInt(u16, num, 10);
try numbers.append(allocator, number);
}
std.mem.sort(u16, numbers.items, {}, struct {
fn lessThanFn(_: void, lhs: u16, rhs: u16) bool {
return lhs < rhs;
}
}.lessThanFn);
return try numbers.toOwnedSlice(allocator);
}
fn part2(buffer: []const u8, allocator: std.mem.Allocator) !void {
const numbers = try parse_to_u16(buffer, allocator);
defer allocator.free(numbers);
var counter: usize = 0;
var size: u16 = 0;
var hash_set = std.AutoHashMap(u16, void).init(allocator);
for (0..numbers.len) |_index| {
const n = numbers[_index];
if (counter == 20) break;
if (hash_set.get(n)) |_| continue;
size += n;
counter += 1;
try hash_set.put(n, {});
}
std.debug.print("{d}\n", .{size});
}
pub fn part3(buffer: []const u8, allocator: std.mem.Allocator) !void {
const numbers = try parse_to_u16(buffer, allocator);
defer allocator.free(numbers);
var initial = numbers[0];
var sets: u32 = 1;
var max_set: u32 = sets;
for (numbers[1..]) |size| {
if (initial != size) {
max_set = @max(sets, max_set);
initial = size;
sets = 1;
} else {
sets += 1;
}
}
max_set = @max(sets, max_set);
std.debug.print("{d}\n", .{max_set});
}
pub fn main() !void {
const allocator = std.heap.page_allocator;
const file = try std.fs.cwd().openFile("src/day3/input.txt", .{});
defer file.close();
const buffer_parts = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
var buffer_parts_split = std.mem.splitScalar(u8, buffer_parts, '\n');
const part1_buffer = buffer_parts_split.next().?;
try part1(part1_buffer, allocator);
const part2_buffer = buffer_parts_split.next().?;
try part2(part2_buffer, allocator);
const part3_buffer = buffer_parts_split.next().?;
try part3(part3_buffer, allocator);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment