本文主要实现基于二度好友的推荐。
数学公式参考于:http://blog.csdn.net/qq_14950717/article/details/52197565
测试数据为自己随手画的关系图
把图片整理成文本信息如下:
a b c d e f y
b c a f g
c a b d
d c a e h q r
e f h d a
f e a b g
g h f b
h e g i d
i j m n q h
j i k l
k j
l j
m i
n i o
o n p
p o q
q i d
r d s t w v
s r t u
t r s u
u s t
v r w x
w r v x
x w v
y a z
z y
每行的第一个为用户,之后的为其好友。
在计算用户之间的推荐分上参考上面博客中的两个数学公式分为两个推荐分。
一个公式为
上面是每个共同好友默认的提供1分,但是在生活中如果次共同好友的好友数比较少,则说明次好友可能更加重要,所以有了下面对每个共同好友加权重的公式
如果好友数差距过大,要对好友数进行开方或对数之类的,这就是要看产品方面对我们的要求了。
说的比较简单,详细理论可以看上面链接的博客。
下面是单机版java的代码:
选创建一个来描述好友之间关系的类
import java.util.List;
public class Score {
//A和B的所有好友数
private int Union;
//A和B的共同好友数
private int Intersection;
//A和B的共同好友列表
private List<Character> l;
//此对象是A和B之间的关系
private char A;
private char B;
//没加权重的得分
private float score;
//对每个共同好友加权重的得分
private double wscore;
public double getWscore() {
return wscore;
}
public void setWscore(double wscore) {
this.wscore = wscore;
}
public float getScore() {
return score;
}
public char getA() {
return A;
}
public void setA(char a) {
A = a;
}
public char getB() {
return B;
}
public void setB(char b) {
B = b;
}
public int getUnion() {
return Union;
}
public void setUnion(int union) {
Union = union;
if(Union!=0){
score=(float) Intersection/Union;
}
}
public int getIntersection() {
return Intersection;
}
public void setIntersection(int intersection) {
Intersection = intersection;
if(Union!=0){
score=(float) Intersection/Union;
}
}
public List getL() {
return l;
}
public void setL(List l) {
this.l = l;
}
@Override
public String toString() {
return "Score{" +
"Union=" + Union +
", Intersection=" + Intersection +
", l=" + l +
", A=" + A +
", B=" + B +
", score=" + score +
", wscore="+wscore+
'}';
}
}
然后写代码对数据进行操作:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class fof {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream("F:\\friends.txt")));
List<Score> scores=new ArrayList<Score>();
String s=null;
List<char[]> l=new ArrayList<char[]>();
Map<Character,Integer> map=new HashMap<Character, Integer>();
while((s=bufferedReader.readLine())!=null){
char[] c = s.replace(" ", "").toCharArray();
l.add(c);
map.put(c[0],c.length-1);
}
for(int i=0;i<l.size();i