Skip to content

Commit

Permalink
Refactor counter implementations in Zig code
Browse files Browse the repository at this point in the history
- Update the `Counter` function in `utils.zig` to use an integer type, improving type safety and performance.
- Add a new test case for the `Counter` function to ensure accuracy.
- Simplify type definitions in `day01.zig` for cleaner and more maintainable code.
  • Loading branch information
thekorn committed Dec 1, 2024
1 parent 9c90096 commit b06e3db
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/day01.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub fn solve(content: []const u8, add_weight: bool) !i32 {
var left = utils.List(i32).init(utils.gpa);
var right = utils.List(i32).init(utils.gpa);

var counter = try utils.Counter(i32, i32).init(utils.gpa);
var counter = try utils.Counter(i32).init(utils.gpa);

while (readIter.next()) |line| {
var lineIter = std.mem.tokenizeSequence(u8, line, " ");
Expand Down
23 changes: 19 additions & 4 deletions src/utils.zig
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ pub fn codeToChar(code: usize) u8 {
}
}

pub fn Counter(comptime K: type, comptime V: type) type {
pub fn Counter(comptime K: type) type {
return struct {
const Self = @This();
items: Map(K, V),
items: Map(K, i32),

pub fn init(alloc: Allocator) !Self {
return .{
.items = Map(K, V).init(alloc),
.items = Map(K, i32).init(alloc),
};
}

Expand All @@ -74,8 +74,23 @@ pub fn Counter(comptime K: type, comptime V: type) type {
}
}

pub fn get(self: *Self, key: K) ?V {
pub fn get(self: *Self, key: K) ?i32 {
return self.items.get(key);
}
};
}

test "utils - Counter" {
const CounterStr = Counter(i32);
var counter = try CounterStr.init(gpa);
try counter.add(1);
try counter.add(1);
try counter.add(2);
try counter.add(3);
try counter.add(5);
try counter.add(6);

try std.testing.expectEqual(2, counter.get(1));
try std.testing.expectEqual(1, counter.get(2));
try std.testing.expectEqual(null, counter.get(10));
}

0 comments on commit b06e3db

Please sign in to comment.