aboutsummaryrefslogtreecommitdiff
path: root/aoc-2020-gleam/src/util/graph.gleam
diff options
context:
space:
mode:
authorTomasz Chojnacki <tomaszchojnacki2001@gmail.com>2023-02-22 13:01:06 +0100
committerTomasz Chojnacki <tomaszchojnacki2001@gmail.com>2023-02-22 13:01:06 +0100
commite83a0b8b0c71dbbce6b3cdb87c77b2740b9f79f8 (patch)
tree06225c03aacf6d5b0c813dfaa3efc961e917bfde /aoc-2020-gleam/src/util/graph.gleam
parent6eaf758850feebd8cfc97c3ead2de2625465a326 (diff)
downloadgleam_aoc2020-e83a0b8b0c71dbbce6b3cdb87c77b2740b9f79f8.tar.gz
gleam_aoc2020-e83a0b8b0c71dbbce6b3cdb87c77b2740b9f79f8.zip
Finish first part of day 7
Diffstat (limited to 'aoc-2020-gleam/src/util/graph.gleam')
-rw-r--r--aoc-2020-gleam/src/util/graph.gleam35
1 files changed, 35 insertions, 0 deletions
diff --git a/aoc-2020-gleam/src/util/graph.gleam b/aoc-2020-gleam/src/util/graph.gleam
new file mode 100644
index 0000000..d9aa5aa
--- /dev/null
+++ b/aoc-2020-gleam/src/util/graph.gleam
@@ -0,0 +1,35 @@
+import gleam/list
+import gleam/iterator.{Iterator} as iter
+import gleam/set.{Set}
+
+fn dfs_helper(
+ neighbours: fn(a) -> Iterator(a),
+ stack stack: List(a),
+ visited visited: Set(a),
+ acc acc: List(a),
+) -> List(a) {
+ case stack {
+ [node, ..stack] ->
+ dfs_helper(
+ neighbours,
+ stack: node
+ |> neighbours
+ |> iter.filter(for: fn(n) { !set.contains(visited, n) })
+ |> iter.to_list
+ |> list.append(stack),
+ visited: visited
+ |> set.insert(node),
+ acc: [node, ..acc],
+ )
+ [] -> list.reverse(acc)
+ }
+}
+
+pub fn dfs(from start: a, with neighbours: fn(a) -> Iterator(a)) -> Iterator(a) {
+ iter.from_list(dfs_helper(
+ neighbours,
+ stack: [start],
+ visited: set.new(),
+ acc: [],
+ ))
+}