Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 27, 2023 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/c36480deb372e064a97ffe14c7fe9350 to your computer and use it in GitHub Desktop.
Save dacr/c36480deb372e064a97ffe14c7fe9350 to your computer and use it in GitHub Desktop.
Playing with scala-graph API / published by https://github.com/dacr/code-examples-manager #41be75cf-c7c1-486c-a9f0-65d1c971d588/ba534a93bd8be5ccf5c5c671c29e8f49d5745782
// summary : Playing with scala-graph API
// keywords : scala, scala-graph, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 41be75cf-c7c1-486c-a9f0-65d1c971d588
// created-on : 2021-12-30T09:03:58+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "2.13.10"
//> using dep "org.scalatest::scalatest:3.2.16"
//> using dep "org.scala-graph::graph-core:1.13.3"
//> using dep "org.scala-graph::graph-dot:1.13.3"
//> using objectWrapper
// ---------------------
// https://www.scala-graph.org/
// https://en.wikipedia.org/wiki/DOT_(graph_description_language)
import org.scalatest._
import org.scalatest.concurrent.Eventually._
import flatspec._, matchers._, OptionValues._
import scalax.collection.Graph // or scalax.collection.mutable.Graph
import scalax.collection.GraphPredef._, scalax.collection.GraphEdge._
import scalax.collection.edge.WDiEdge
import scalax.collection.edge.Implicits._
case class Item(name: String)
class ThatSpec extends AnyFlatSpec with should.Matchers {
"Graph API" should "be able to create simple undirected graphs" in {
val g1 = Graph(1 ~ 3, 5)
g1.edges.size shouldBe 1
g1.nodes.size shouldBe 3
val g2 = Graph("A" ~ "B", "B" ~ "C", "A" ~ "D")
g2.edges.size shouldBe 3
g2.nodes.size shouldBe 4
}
it should "be able to create simple directed graphs" in {
val wheel = Graph(
Item("A") ~> Item("B"),
Item("B") ~> Item("C"),
Item("C") ~> Item("D"),
Item("D") ~> Item("A")
)
wheel.edges.size shouldBe 4
wheel.nodes.size shouldBe 4 // and not 5 of course
}
it should "be able to create weighted directed/undirected graphs" in {
// https://www.scala-graph.org/guides/core-traversing.html
val graph = Graph(
1 ~ 2 % 4,
2 ~ 3 % 2,
1 ~> 3 % 5,
1 ~ 5 % 3,
3 ~ 5 % 2,
3 ~ 4 % 1,
4 ~> 4 % 1,
4 ~> 5 % 0
)
val sp0 = graph.get(3) shortestPathTo graph.get(1)
}
// TODO - to be continued...
}
org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[ThatSpec].getName))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment