summaryrefslogtreecommitdiff
path: root/graph/src/adlist.rs
blob: 18ad770e7c61eb85fc20384562430325648d9f2b (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#![warn(missing_docs)]
//! This file implements a data type that implements the trait
//! [`Graph`][super::Graph].  This data type represents graphs using
//! adjacency lists internally.

use super::{ExtGraph, Graph};
use crate::error::Error;

// #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
// struct ALEdge {
//     to: usize,
// }

// impl ALEdge {
//     fn new(to: usize) -> Self {
//         Self { to }
//     }
// }

#[derive(Debug, Clone, Default)]
struct ALNode {
    children: Vec<usize>,
}

impl ALNode {
    fn new(children: Vec<usize>) -> Self {
        Self { children }
    }
}

/// The graph implemented using adjacency lists.
#[derive(Debug, Clone, Default)]
pub struct ALGraph {
    nodes: Vec<ALNode>,
}

impl Graph for ALGraph {
    type Iter<'a> = std::iter::Copied<std::slice::Iter<'a, usize>>;

    #[inline]
    fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    #[inline]
    fn nodes_len(&self) -> usize {
        self.nodes.len()
    }

    #[inline]
    fn children_of(&self, node_id: usize) -> Result<Self::Iter<'_>, Error> {
        match self.nodes.get(node_id) {
            Some(node) => Ok(node.children.iter().copied()),
            None => Err(Error::IndexOutOfBounds(node_id, self.nodes_len())),
        }
    }

    #[inline]
    fn degree(&self, node_id: usize) -> Result<usize, Error> {
        match self.nodes.get(node_id) {
            Some(node) => Ok(node.children.len()),
            None => Err(Error::IndexOutOfBounds(node_id, self.nodes_len())),
        }
    }

    #[inline]
    fn is_empty_node(&self, node_id: usize) -> Result<bool, Error> {
        match self.nodes.get(node_id) {
            Some(node) => Ok(node.children.is_empty()),
            None => Err(Error::IndexOutOfBounds(node_id, self.nodes_len())),
        }
    }

    fn has_edge(&self, source: usize, target: usize) -> Result<bool, Error> {
        if !self.has_node(source) {
            Err(Error::IndexOutOfBounds(source, self.nodes_len()))
        } else if !self.has_node(target) {
            Err(Error::IndexOutOfBounds(target, self.nodes_len()))
        } else {
            Ok(self.nodes.get(source).unwrap().children.contains(&target))
        }
    }
}

impl ExtGraph for ALGraph {
    fn extend(&mut self, edges: impl IntoIterator<Item = usize>) -> Result<usize, Error> {
        let mut new_node_children = Vec::new();

        for edge_to in edges.into_iter() {
            if !self.has_node(edge_to) {
                return Err(Error::IndexOutOfBounds(edge_to, self.nodes_len()));
            }

            new_node_children.push(edge_to);
        }

        let new_node = ALNode::new(new_node_children);

        self.nodes.push(new_node);

        Ok(self.nodes.len() - 1)
    }
}

// TODO: Add a way to build a graph by its raw adjacency list representation.
impl From<Vec<Vec<usize>>> for ALGraph {
    fn from(adlist: Vec<Vec<usize>>) -> Self {
        let nodes: Vec<ALNode> = adlist.iter().cloned().map(ALNode::new).collect();
        Self { nodes }
    }
}

#[cfg(test)]
mod algraph_test {
    use super::*;

    #[test]
    fn test_graph_apis() -> Result<(), Error> {
        let mut graph = ALGraph::default();

        assert!(graph.is_empty());

        graph.extend(std::iter::empty())?;

        graph.extend([0].iter().copied())?;
        graph.extend([0, 1].iter().copied())?;
        graph.extend([0, 2].iter().copied())?;
        graph.extend([1, 2].iter().copied())?;
        graph.extend([1, 2, 3].iter().copied())?;

        let graph = graph;

        assert_eq!(graph.nodes_len(), 6);

        assert_eq!(graph.children_of(5)?.collect::<Vec<_>>(), vec![1, 2, 3]);

        assert_eq!(graph.degree(4)?, 2);

        assert!(graph.is_empty_node(0)?);
        assert!(!graph.is_empty_node(1)?);

        assert!(graph.has_edge(3, 2)?);
        assert!(!graph.has_edge(3, 1)?);
        assert_eq!(graph.has_edge(3, 6), Err(Error::IndexOutOfBounds(6, 6)));

        Ok(())
    }

    #[test]
    fn test_extending_algraph_normal() -> Result<(), Error> {
        let mut graph = ALGraph::default();

        let new = graph.extend(std::iter::empty())?;

        println!("new index = {new}");

        println!("new graph = {graph:?}");

        let new = graph.extend([0].iter().copied())?;

        println!("new index = {new}");

        println!("new graph = {graph:?}");

        let new = graph.extend([0, 1].iter().copied())?;

        println!("new index = {new}");

        println!("new graph = {graph:?}");

        Ok(())
    }

    #[test]
    fn test_extending_algraph_error() -> Result<(), Error> {
        let mut graph = ALGraph::default();

        graph.extend(std::iter::empty())?;

        graph.extend([0].iter().copied())?;

        assert_eq!(
            graph.extend([2].iter().copied()),
            Err(Error::IndexOutOfBounds(2, 2))
        );

        Ok(())
    }
}