Skip to content

Instantly share code, notes, and snippets.

@ALANVF
Last active May 23, 2024 09:09
Show Gist options
  • Save ALANVF/ca57fdf76da885acb657db667ca9e2ee to your computer and use it in GitHub Desktop.
Save ALANVF/ca57fdf76da885acb657db667ca9e2ee to your computer and use it in GitHub Desktop.
type T
class Graph[T] {
my vertices (Set[Vertex[T]])
init [new] {
vertices = Set[Vertex[T]] #[]
}
on [numVertices] (Int) is getter {
my counted = Set[Vertex[T]] #[]
my count = 0
for my vertex in: vertices {
count += vertex[countVertices: counted]
}
return count
}
on [numEdges] (Int) is getter {
my count = 0
for my vertex in: vertices {
count += vertex.edges.size
}
return count
}
on [add: start (Vertex[T]), end (Vertex[T]) weight: (Int)] {
vertices
-> [add: start]
-> [add: end]
start[add: end :weight]
}
on [remove: start (Vertex[T]), end (T)] {
start[remove: end]
if start.edges.size ?= 0 && vertices[none: $0[hasEdge: start]] {
vertices[remove: start]
}
if end.edges.size ?= 0 && vertices[none: $0[hasEdge: end]] {
vertices[remove: end]
}
}
on [edgeWeight: start (Vertex[T]), end (Vertex[T])] (Int) {
return start[weightOfEdge: end]
}
on [depthFirst: start (Vertex[T]) traverse: (Func[Void, T])] {
start[depthFirstTraverse: traverse visited: Set[Vertex[T]] #[]]
}
on [breadthFirst: start (Vertex[T]) traverse: (Func[Void, T])] {
traverse[call: start.value]
start[breadthFirstTraverse: traverse visited: Set[Vertex[T]] #[start]]
}
}
type T
class Vertex[T] is friend Graph[T] {
my value (T)
my edges (Dict[This, Int]) is hidden
init [new: value (T)] {
_.value = value
edges = #()
}
on [add: end (This) weight: (Int)] {
edges[addNew: end] = weight
}
on [remove: end (This)] {
edges[remove: end]
}
on [hasEdge: end (This)] {
return edges[hasKey: end]
}
on [weightOfEdge: end (This)] {
return edges[at: end]
}
on [countVertices: counted (Set[This])] (Int) is hidden {
if counted[has: this] {
return 0
} else {
counted[add: this]
my count = 1
for my vertex, _ in: edges {
count += vertex[countVertices: counted]
}
return count
}
}
on [depthFirstTraverse: func (Func[Void, T]) visited: (Set[This])] is hidden {
if visited[has: this] => return
func[call: value]
visited[add: this]
for my vertex, _ in: edges {
vertex[depthFirstTraverse: func :visited]
}
}
on [breadthFirstTraverse: func (Func[Void, T]) visited: (Set[This])] is hidden {
if visited[has: this] => return
visited[add: this]
for my vertex, _ in: edges => func[call: vertex.value]
for my vertex, _ in: edges => vertex[breadthFirstTraverse: func :visited]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment