Skip to main content

quickstart/
quickstart.rs

1//! Build a small hypergraph, read it back, and compute one statistic.
2//!
3//! Run it with `cargo run -p hypergraph-rs --example quickstart`.
4
5use hypergraph_rs::algorithms::connected::number_connected_components;
6use hypergraph_rs::Hypergraph;
7
8fn main() {
9    // Nodes, edges and memberships carry no value here, so all three types are `()`.
10    let mut h: Hypergraph<(), (), ()> = Hypergraph::new();
11
12    // An edge joins any number of nodes. Nodes that do not exist yet are created.
13    h.add_edge(
14        vec!["ana".into(), "bo".into(), "cy".into()],
15        Some("club".into()),
16        (),
17    )
18    .unwrap();
19    h.add_edge(
20        vec!["bo".into(), "cy".into(), "di".into(), "ed".into()],
21        Some("choir".into()),
22        (),
23    )
24    .unwrap();
25    h.add_edge(vec!["fay".into(), "gus".into()], Some("pair".into()), ())
26        .unwrap();
27
28    // Listings keep the order in which things were added.
29    println!("nodes: {:?}", h.node_ids());
30    println!("edges: {:?}", h.edge_ids());
31    println!("members of choir: {:?}", h.members("choir").unwrap());
32    println!("bo belongs to: {:?}", h.memberships("bo").unwrap());
33    assert_eq!(h.node_ids(), ["ana", "bo", "cy", "di", "ed", "fay", "gus"]);
34    assert_eq!(h.members("choir").unwrap(), ["bo", "cy", "di", "ed"]);
35    assert_eq!(h.memberships("bo").unwrap(), ["club", "choir"]);
36
37    // One statistic: the number of connected components. "pair" shares no member with the
38    // other two edges, so there are two.
39    let parts = number_connected_components(&h);
40    println!("connected components: {parts}");
41    assert_eq!(parts, 2);
42}