2016-10-29 1 views
0

J'ai essayé d'utiliser la bibliothèque GraphStream pour trouver le chemin le plus court entre 2 nœuds dans un graphique. À la fin, je suis en mesure d'imprimer les bords du chemin (it.foreach(println)) mais je ne peux pas accéder à un élément à la fois. Voici le code:Comment utiliser la bibliothèque GraphStream pour Scala

import org.graphstream.algorithm.Dijkstra; 
import org.graphstream.graph.Edge; 
import org.graphstream.graph.Graph; 
import org.graphstream.graph.Node; 
import org.graphstream.graph.Path; 
import org.graphstream.graph.implementations.SingleGraph; 
import scala.collection.JavaConverters._ 


object MainApp extends App{ 


     def exampleGraph():Graph={ 
        val g:Graph = new SingleGraph("example"); 
        g.addNode("N1_S1"); 
        g.addNode("N1_J1"); 
        g.addNode("N1_H1"); 
        g.addNode("N1_J2"); 
        g.addNode("N1_H2"); 
        g.addNode("N1_W1"); 
        var e:Edge=g.addEdge("N1_S1-N1_J1", "N1_S1", "N1_J1") 
        e.addAttribute("length",Int.box(6)) 
        e=g.addEdge("N1_J1-N1_H1", "N1_J1", "N1_H1") 
        e.addAttribute("length",Int.box(8)) 
        e=g.addEdge("N1_J1-N1_J2", "N1_J1", "N1_J2") 
        e.addAttribute("length",Int.box(8)) 
        e=g.addEdge("N1_J2-N1_H2", "N1_J2", "N1_H2") 
        e.addAttribute("length",Int.box(4)) 
        e=g.addEdge("N1_J2-N1_W1", "N1_J2", "N1_W1") 
        e.addAttribute("length",Int.box(10)) 

        return g 
     } 

    val g:Graph = exampleGraph(); 
    g.display(false); 

    val dijkstra:Dijkstra = new Dijkstra(Dijkstra.Element.EDGE, null, "length"); 

    dijkstra.init(g); 

    dijkstra.setSource(g.getNode("N1_S1")); 

    println(dijkstra.getPath(g.getNode("N1_W1"))); 
    val myPath:Path=dijkstra.getPath(g.getNode("N1_W1")) 
    val it=(myPath.getEachEdge).asScala 
    println("edges") 
    it.foreach(println) 
} 

Le problème est que le prototype de getEachEdge est getEachEdge[T <: Edge](): Iterable[_ <: T] et asScala renvoie un Iterable[_ <: Nothing]. Donc, la dernière question est "Comment puis-je accéder à chaque élément du chemin le plus court?"

+0

Quelle version scala utilisez-vous? –

Répondre

2

Je ne sais pas pourquoi, mais vous devez explicitement annoter le type.

myPath.getEachEdge[Edge].asScala 

Vous pouvez obtenir des exceptions d'exécution à l'exécution si vous spécifiez le mauvais sous-type.

Ce qui suit jette une ClassCastException:

@ trait OtherEdge extends Edge 
defined trait OtherEdge 
@ myPath.getEachEdge[OtherEdge].asScala.head 
java.lang.ClassCastException: org.graphstream.graph.implementations.AbstractEdge cannot be cast to $sess.cmd17$OtherEdge 
    $sess.cmd18$.<init>(cmd18.sc:1) 
    $sess.cmd18$.<clinit>(cmd18.sc:-1) 
+0

Ça marche! Tu m'as sauvé la vie!! –

1

Essayez d'aider le compilateur avec une annotation de type:

val it: Iterable[Edge] = myPath.getEachEdge.asScala 
+0

Aussi cette solution fonctionne !! Merci!! –