使用java来构造关联矩阵
程序如下
FileUtil.java
package com.gongjiao;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
/**
* 用来读取文件和保存文件
* @author Administrator
*
*/
public class FileUtil {
// //读取文件
public static ArrayList<String> getFile(String filename) {
BufferedReader br = null;
ArrayList<String> list = new ArrayList<String>();
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(
new File(filename)), "GBK"));
String str = br.readLine();
while (str != null) {
list.add(str);
str = br.readLine();
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
// 保存文件
public static void savefile(List<String> list, String filename) {
BufferedWriter bout = null;
try {
bout = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filename), "GBK"));
for (String str : list) {
if (str != null && !str.equals("")) {
bout.write(str);
bout.newLine();
}
}
bout.flush();
bout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
IncidenceMatrix.java
package com.supernetwork;
import java.util.ArrayList;
/**
* 利用边和节点来构造关联矩阵
* @author Administrator
*/
public class IncidenceMatrix
{
public static void main(String[] args)
{
ArrayList<String> strList = new ArrayList<String>();
//边
ArrayList<String> edges = FileUtil.getFile("edge.txt");
//节点
ArrayList<String> nodes = FileUtil.getFile("node.txt");
int[][] matrix = new int[nodes.size()][edges.size()];
for (int i = 0; i < nodes.size(); i++)
{
for (int j = 0; j < edges.size(); j++)
{
matrix[i][j] = 0;
}
}
for (int i = 0; i < nodes.size(); i++)
{
for (int j = 0; j < edges.size(); j++)
{
if (edges.get(j).contains(nodes.get(i)))
{
matrix[i][j] = 1;
}
}
}
for (int i = 0; i < nodes.size(); i++)
{
StringBuffer sb = new StringBuffer();
if( i == 0 ){
sb.append("[[");
}else {
sb.append("[");
}
for (int j = 0; j < nodes.size(); j++)
{
sb.append(matrix[i][j] + ",");
}
String str = sb.toString().substring(0,sb.toString().length() - 1);
if( i == nodes.size() - 1){
str = str + "]]";
}else{
str = str + "],";
}
strList.add(str);
}
FileUtil.savefile(strList,"incidenceMatrix.txt");
System.out.println("成功!!");
}
}