1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
const std = @import("std");
fn countCommon(
allocator: std.mem.Allocator,
a1: []const []const u8,
a2: []const []const u8,
) !usize {
var count: usize = 0;
var h = std.StringHashMap(u32).init(allocator);
defer h.deinit();
for (a1) |s| {
const entry = try h.getOrPut(s);
if (entry.found_existing) {
entry.value_ptr.* += 1;
} else {
entry.value_ptr.* = 1;
}
}
for (a2) |s| {
const entry = try h.getOrPut(s);
if (entry.found_existing) {
entry.value_ptr.* += 1;
} else {
entry.value_ptr.* = 1;
}
}
var it = h.iterator();
while (it.next()) |e| {
if (e.value_ptr.* >= 2) {
count += 1;
}
}
return count;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
std.debug.assert(gpa.detectLeaks() == false);
std.debug.assert(gpa.deinit() == .ok);
}
const allocator = gpa.allocator();
const a1 = [_][]const u8{ "perl", "weekly", "challenge" };
const a2 = [_][]const u8{ "raku", "weekly", "challenge" };
const a3 = [_][]const u8{ "perl", "raku", "python" };
const a4 = [_][]const u8{ "python", "java" };
const a5 = [_][]const u8{ "guest", "contribution" };
const a6 = [_][]const u8{ "fun", "weekly", "challenge" };
std.debug.print("{}\n", .{try countCommon(allocator, &a1, &a2)});
std.debug.print("{}\n", .{try countCommon(allocator, &a3, &a4)});
std.debug.print("{}\n", .{try countCommon(allocator, &a5, &a6)});
}
|