import scala.collection.mutable
class RelationBean {
//起始节点
private var _fromNode: String = "null"
def fromNode: String = _fromNode
def fromNode_=(value: String): Unit = {
_fromNode = value
}
//指向节点
private var _toNode: String = "null"
def toNode: String = _toNode
def toNode_=(value: String): Unit = {
_toNode = value
}
//属性
private var _info: Set[String] = new mutable.HashSet[String].toSet
def info: Set[String] = _info
def info_=(value: Set[String]): Unit = {
_info = value
}
def canEqual(other: Any): Boolean = other.isInstanceOf[RelationBean]
override def equals(other: Any): Boolean = other match {
case that: RelationBean =>
(that canEqual this) && (_fromNode == that._fromNode && _toNode == that._toNode)
case _ => false
}
override def toString: String = "{fromNode:" + fromNode + ",toNode:" + toNode + ",info:" + info.toString() + "}"
}
object RelationBean {
def apply: RelationBean = new RelationBean()
}
import RelationBean
import scala.collection.mutable
object PageRank {
//计算出度和入度
private def degree(relationset: Set[RelationBean]): (Map[String, Set[String]], Map[String, Set[String]]) = {
val indegree = new mutable.HashMap[String, Set[String]]()
val outdegree = new mutable.HashMap[String, Set[String]]()
relationset.foreach(rela => {
outdegree.put(rela.fromNode, outdegree.getOrElse(rela.fromNode, new mutable.HashSet[String]()).+(rela.toNode).toSet)
indegree.put(rela.toNode, indegree.getOrElse(rela.toNode, new mutable.HashSet[String]()).+(rela.fromNode).toSet)
})
(indegree.toMap, outdegree.toMap)
}
//计算权重
private def weight(indegree: Map[String, Set[String]], outdegree: Map[String, Set[String]]): Map[String, Double] = {
var oldweight = new mutable.HashMap[String, Double]()
val newweight = new mutable.HashMap[String, Double]()
var f = 0
while (f < 3) {
indegree.foreach(a => {
var w = 0.0
a._2.foreach(b => {
w += (oldweight.getOrElse(b, 1.0) / outdegree(b).size)
})
newweight.put(a._1, w)
})
oldweight.clear()
oldweight = newweight.clone()
f += 1
}
newweight.toMap
}
def run(relationset: Set[RelationBean]): Map[String, Double] = {
val (in, out) = this.degree(relationset)
weight(in, out)
}
}
自用,待优化