Skip to main content

generate_random_path

Function generate_random_path 

Source
pub fn generate_random_path<G>(
    graph: G,
    source: G::NodeId,
    length: usize,
    seed: Option<u64>,
) -> Vec<G::NodeId>
Expand description

Return a random path (or random walk) on the graph.

The next node to visit is selected uniformly at random from the outgoing neighbors. If a node has no outgoing neighbor, the path will stop early. The graph may be directed or not.

§Arguments:

  • graph - Graph on which the random walk is done.
  • source - Starting node of the path.
  • length - Maximum length of the path.
  • seed - seed of the random number generator that chooses the next node.

§Returns

A vector of the visited nodes including the initial node source.

§Example

use petgraph::graph::DiGraph;
use rustworkx_core::traversal::generate_random_path;

let mut graph: DiGraph<(), ()> = DiGraph::with_capacity(3, 3);
let a = graph.add_node(());
let b = graph.add_node(());
let c = graph.add_node(());
graph.extend_with_edges([(a, b), (b, c), (c, a)]);
let path = generate_random_path(&graph, a, 3, Some(5));
assert_eq!(path, vec![a, b, c, a]);