Skip to content

Commit d2d2735

Browse files
committed
feat(2024): add Graph data structure
1 parent d9a7093 commit d2d2735

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

2024/Graph.zig

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
const std = @import("std");
2+
const Allocator = std.mem.Allocator;
3+
4+
allocator: Allocator,
5+
links: std.StringHashMap(std.BufSet),
6+
7+
const Self = @This();
8+
9+
pub fn init(allocator: Allocator) Self {
10+
return Self{
11+
.links = std.StringHashMap(std.BufSet).init(allocator),
12+
.allocator = allocator,
13+
};
14+
}
15+
16+
pub fn addLink(self: *Self, u: []const u8, v: []const u8) !void {
17+
if (self.links.contains(u)) {
18+
try self.links.getPtr(u).?.insert(v);
19+
} else {
20+
var bufset = std.BufSet.init(self.allocator);
21+
try bufset.insert(v);
22+
try self.links.put(u, bufset);
23+
}
24+
}
25+
26+
pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
27+
_ = fmt;
28+
_ = options;
29+
var links_it = self.links.iterator();
30+
while (links_it.next()) |e| {
31+
const u = e.key_ptr.*;
32+
try writer.print("\n{s}\n └[", .{u});
33+
var v_it = e.value_ptr.iterator();
34+
while (v_it.next()) |v| {
35+
try writer.print("{s},", .{v.*});
36+
}
37+
try writer.print("]", .{});
38+
}
39+
}
40+
41+
pub fn toDotFile(self: *Self, allocator: Allocator) !void {
42+
const file_path = "graph.dot";
43+
const file = try std.fs.cwd().createFile(file_path, .{});
44+
var fw = file.writer();
45+
46+
try fw.print("strict digraph G {{", .{});
47+
var it = self.links.iterator();
48+
while (it.next()) |e| {
49+
const u = e.key_ptr.*;
50+
try fw.print("\n {s} -> {{", .{u});
51+
var v_it = e.value_ptr.iterator();
52+
while (v_it.next()) |v| {
53+
try fw.print("{s} ", .{v.*});
54+
}
55+
try fw.print("}}", .{});
56+
}
57+
try fw.print("\n}}", .{});
58+
59+
// Try to run 'dot' command to compile .dot file to svg
60+
var child_process = std.process.Child.init(&[_][]const u8{ "dot", "-Tsvg", file_path, "-o", "graph.svg" }, allocator);
61+
child_process.stdout_behavior = .Pipe;
62+
child_process.stderr_behavior = .Pipe;
63+
try child_process.spawn();
64+
_ = try child_process.wait();
65+
}
66+
67+
pub fn findCliques(self: *Self) void {
68+
_ = self;
69+
}

0 commit comments

Comments
 (0)