i'm creating graph nodes (with integer value) , edges (source, destination , weight) reading file format
1 51 1
1 72 2
1 77 1
etc.
set<node> nodes = new hashset<node>(); //a set of nodes of graph arraylist<node> nodelist = new arraylist<node>(); arraylist<edge> edgelist = new arraylist<edge>(); ... node node1=new node(integer.parseint(temprelation[0])); node node2=new node(integer.parseint(temprelation[1])); nodes.add(node1); nodes.add(node2); edge edge = new edge(node1, node2, integer.parseint(temprelation[2])); edgelist.add(edge); } the class node has field "number of neighbors", , wanted go through edges , increment number of neighbors whenever either source or destinatio appears.
for (int edge=0; edge<graph.getedges().size(); edge++){ graph.getedges().get(edge).getsource().neighborup(); graph.getedges().get(edge).getdestination().neighborup(); } strangely enough, although objects seem same (i checked equals), counter not go up. e.g., 1, goes once first edge, not go when try increment when second edge concerned. when considering second edge before incrementing, somehow shows number of neighbors 0, although incremented number of neighbors of first node in first edge. if did printouts of counters before , after incrementation 0 1 0 1 if other objects concerned.
i assume use java. problem creation of graph, every time when create edge create new objects nodes:
node node1=new node(integer.parseint(temprelation[0])); node node2=new node(integer.parseint(temprelation[1])); the set contains 1 copy every integer, edges contain different instancies.
to solve can create map of parsed nodes , @ every iteration instead of creating object integer, check if have created object integer:
//one global object map<integer,node> map = new hashmap<integer,node> (); ... integer val = integer.parseint(temprelation[0]); if (map.get(val)==null) { map.put(val, new node(val)); } node node1 = map.get(val); val = integer.parseint(temprelation[1]); if (map.get(val)==null) { map.put(val, new node(val)); } node node2 = map.get(val);
Comments
Post a Comment