在java图中创建具有权重的节点

时间:2015-04-01 06:06:42

标签: java algorithm graph

我正在创建一个程序来为参考书目数据集创建图表。图形是定向的,具有“作者”节点和“纸”节点,并且有两种类型的边(作者到纸边,纸到边缘)。

我希望得到一个关于我创造的内容是否有意义的意见。现在,当我想从一个节点获取outEdge和inEdge时,它会产生正确的结果。但我不确定这种实现在方法,设计和算法方面是否正确。

另外,我在为节点分配权重时遇到问题。我想问一下我怎么能这样做。现在,我尝试的内容如下:

for (String item : CandidateAuthorType1Unique) {
    double weight = Collections.frequency(CandidateAuthorType1, item);
    n.setWeight(item,weight);;
    System.out.println(n.getName() + " : " + n.getWeight());
}

但是,使用setWeight后,getName()方法返回null。这意味着分配的权重未分配给某个项目。我想知道如何更新某个项目的重量。

如果我使用

for (String item : CandidateAuthorType1Unique) {
    double weight = Collections.frequency(CandidateAuthorType1, item);
    n = new Node(item,weight);
    System.out.println(n.getName() + " : " + n.getWeight());
}   

这是否意味着每次创建新节点n时,旧的n节点都不会被存储?如何检查所创建的每个节点及其重量?

我想请你输入这个节目。任何输入都对我有用。谢谢。

主要课程:Ranker.java

import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.sql.*;

public class Ranker {

    static Graph g;
    static Node n;
    static Edge e;
    static HashMap nodeMap;   // maps Integer NodeIDs to Node object
    String id;
    double weight;

    Ranker() {
            g = new Graph();
            nodeMap = new HashMap();
            n = new Node(id,weight);
    }

    public static void main (String[] args) throws ClassNotFoundException, SQLException, IOException, IllegalArgumentException, IllegalAccessException{

        Ranker Ranker = new Ranker();
        Connection connect = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        HashMap nodeMap =  new HashMap();   // maps Integer NodeIDs to Node objects

        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager.getConnection("jdbc:mysql://localhost/arnetminer?"+"user=root&password=1234");
        preparedStatement = connect.prepareStatement("Select fr,t,ty from subedge");

        resultSet = preparedStatement.executeQuery();
        int i=0;

        while(resultSet.next()) {
           g.addEdgeForIndexing(resultSet.getInt(1),resultSet.getInt(2),resultSet.getInt(3));
           i++;             
           System.out.println( "edges added to G = "+i);
        }       

        System.out.println("Loaded " + g.nodeCount() + " nodes.");

        buildNodes();

        System.out.println("Enter first author key:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String authorkey1 = br.readLine(); 
        int authorID1 = Integer.parseInt(authorkey1);
        String AuthorID1 = "A"+authorID1;
        ArrayList<String> p1 = g.getOutEdgesToP(AuthorID1);
        System.out.println("P1 = " + p1);

        ArrayList<String> p2 = new ArrayList<String>();
        for (int j = 0; j<p1.size();j++){
            ArrayList<String> temp = g.getOutEdgesToP(p1.get(j));
            if (temp!=null)
            p2.addAll(temp);
        }
        System.out.println("P2 = " +p2);

        ArrayList<String> CandidateAuthorType1 = new ArrayList<String>();
        for (int k = 0; k<p2.size(); k++){
            ArrayList<String> temp = g.getInEdgesFromPtoA(p2.get(k));
            if(temp!=null)
                CandidateAuthorType1.addAll(temp);
        }
        System.out.println("Candidate Author Type 1= " + CandidateAuthorType1);

        ArrayList<String> CandidateAuthorType1Unique = removeDuplicates(CandidateAuthorType1);
        System.out.println("-----------------------------------------------");
        System.out.println("Candidate author type 1 and author node weight:");
        for (String item : CandidateAuthorType1Unique) {
            double weight = Collections.frequency(CandidateAuthorType1, item);
            n.setWeight(item,weight);;
            System.out.println(n.getName() + " : " + n.getWeight());
        }       

        ArrayList<String> CandidatePaperType1 = new ArrayList<String>();
        for (int l = 0; l<CandidateAuthorType1.size(); l++){
            ArrayList<String> temp = g.getOutEdgesToP(CandidateAuthorType1.get(l));
            if(temp!=null)
                CandidatePaperType1.addAll(temp);
        }
        System.out.println("Candidate Paper Type 1= " + CandidatePaperType1);
    }   


    private static ArrayList<String> removeDuplicates(ArrayList<String> element){
        ArrayList<String> result = new ArrayList<>();
        HashSet<String> set = new HashSet<>();
        for (String item : element) {
            if (!set.contains(item)) {
            result.add(item);
            set.add(item);
            }
        }
        return result;  
    }

    private static void buildNodes() 
    {
        String nodeID;
        double weight = 0;
        Node n;
        Iterator it = g.nodeIteratorInitial();
        while (it.hasNext()) {
          nodeID = (String) it.next(); 
          if (!nodeMap.containsKey(nodeID)){
              n = new Node(nodeID,weight);
              nodeMap.put(nodeID, 0);
          }
        }
    }
}

Graph.java

import java.lang.reflect.Field;
import java.util.*;

public class Graph {

    private HashSet<String>  nodeIDs;   
    public HashMap<Integer, String> nodeIDsWithTN;
    public HashMap<Integer, String> TNMap;  
    private HashMap<String, ArrayList<String>>  edges;
    private HashMap<String, ArrayList<String>>  reverse;
    private int numNodes;
    private int numEdges;
    private int numReverse;

    public Graph() {
        edges = new HashMap<String, ArrayList<String>>();
        reverse = new HashMap<String, ArrayList<String>>();
        nodeIDs = new HashSet<String>();
        nodeIDsWithTN = new HashMap<Integer, String>();
        TNMap = new HashMap<Integer, String>();
        new HashSet();
    }

    public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {
        String From = ""+from;
        String To = ""+to;
        int type = T; 
        if(T==1)
        {
            From="A"+from;
            To="P"+to;
        }
        else if(T==2)
        {
            From="P"+from;
            To="P"+to;
        }           
        else
            System.out.println("T ="+T+" value undefined");

            Edge e = new Edge(From,To,type);

            nodeIDs.add(e.From);
            nodeIDs.add(e.To);

            ArrayList<String> tmp = null;
            if (edges.containsKey(e.From))
              tmp = (ArrayList<String>) edges.get(e.From);
            else {
              tmp = new ArrayList<String>();
              edges.put(e.From,tmp);
            }
            tmp.add(e.To);

            ArrayList<String> tmp2 = null;
            if (reverse.containsKey(e.To))
              tmp2 = (ArrayList<String>) reverse.get(e.To);
            else {
              tmp2 = new ArrayList<String>();
              reverse.put(e.To,tmp2);
            }
            tmp2.add(e.From);
    }

    public int nodeCount() {
        if(nodeIDs.size() > 0) 
            return nodeIDs.size();
            // else return numNodes;
        return numEdges;
    }

    public int countInEdges(Integer key) {
        if (!reverse.containsKey(key)) return 0;
            return ((ArrayList<?>) reverse.get(key)).size();
    }

    public int countOutEdges(Integer key) {
        if (!edges.containsKey(key)) return 0;
            return ((ArrayList<?>) edges.get(key)).size();
    }

    public ArrayList<String> getInEdgesFromPtoA(String id) {
        if (!reverse.containsKey(id)) return null;  
            ArrayList<String> a = reverse.get(id);
            ArrayList<String> result = new ArrayList<String>();
                for(int j=0;j<a.size();j++){
                      if(a.get(j).startsWith("A")){
                          result.add(a.get(j));                           
                      }
                 }
        return result;
    }

    public ArrayList<String> getOutEdgesToP(String id) {
        if (!edges.containsKey(id)) return null;    
            ArrayList<String> a = edges.get(id);
            ArrayList<String> result = new ArrayList<String>();
            for(int j=0;j<a.size();j++){
              if(a.get(j).startsWith("P")){
              result.add(a.get(j));                           
              }
            }
        return result;
    }

    public Iterator<String> nodeIteratorInitial() {
        return nodeIDs.iterator();
    }
}

Edge.java

public class Edge {


    String From;
    String To;
    int type;
    private static int counter = 0;
    public Edge(String From, String To, int type) {
        this.From = new String(From);
        this.To = new String(To);
        this.type = type;
    //  System.out.println("edges added from " + From + " to " +  To + " with type "+ type);
    }

    public String getFrom(){
        return From;
    }

    public String getTo(){
        return To;
    }

    public int getType(){
        return type;
    }

    public void setFrom(String From){
        this.From = From;
    }

    public void setTo(String To){
        this.To = To;
    }

    public void setType(int type){
        this.type = type;
    }
}

Node.java

public class Node {

      String id;
      double weight;
      private static int counter = 0;

      public Node(String id,double weight) {
          this.id = id;
          this.weight = weight;;

      }

      public double getWeight(){
            return weight;
      }

      public String getName() {
           return id;
      }

      public void setWeight(String id, double weight){
         if (this.id==id){
          this.weight=weight;}
          System.out.println("The node " + id + " has weight " + weight);
      }


      public void setName(String id){
          this.id=id;
      }

}

1 个答案:

答案 0 :(得分:1)

当您在n构造函数中初始化Ranker()时,在调用构造函数时,String id尚未分配,因此始终包含值null。因此,您的Node n也会将id作为null。这就是为什么权重未在setWeight(String id, double weight)函数中更新的原因,新的idnull进行比较,false总是返回n = new Node(id,weight)因此权重没有&Ranker() #39; t得到更新。

您可以在代码中进行以下更改

1)删除n.setWeight(item,weight)构造函数中的main初始化。

2)在Ranker课程的if (n == null) n = new Node(item, weight); n.setWeight(item, weight); 方法中添加以下行代替{{1}}。

{{1}}