我有一项作业,要求我获取一个大型数据集,将其存储在数组中,然后创建以各种方式解释数据的方法。我得到的文件数据的形式如下:
0 138
0 139
0 140
0 141
0 142
0 799
4 1
4 10
4月12日
4月18日
等等...(非常大)
这些数据应该代表人们的社交网络,其中的数字代表个人。每行包含一个左边的人,他“信任”右边的人。我应该解释这些数据,以便我可以找到某个人信任的所有人、有多少人信任某个人,以及如何找到最值得信任的人。但是,我完全不知道如何编写这些方法,所以我想知道你们是否可以帮助我。这是我到目前为止的代码:
public class SocialNetwork {
static Scanner scanner = new Scanner(System.in);
static void findTrusted()
{
System.out.println("Please input person number you would like to find Trustees for");
trustee = (scanner.next());
}
public static void main(String[] args){
File inData = new File("dataset.txt");
ArrayList<Integer> links = new ArrayList<Integer>();
try
{
Scanner in = new Scanner(inData);
in.nextLine();
in.nextLine();
in.nextLine();
in.nextLine();
while (in.hasNext())
{
int trustee = in.nextInt();
int trusted = in.nextInt();
links.add(trustee);
links.add(trusted);
}
in.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
如您所见,我的 findTrustee 方法中的内容很少。我只是不知道从哪里开始。我想出了一些伪代码来尝试剖析需要做什么:
- 提示用户输入哪个人(整数)来查找他/她的受托人
- 搜索输入的人(整数)的数组列表链接
- 在以请求的人员开头的行的右侧打印所有人员(整数)
但是,我不太知道该怎么做。
最佳答案
结构links
并不能真正帮助你。它没有“从”和“到”的概念。您将人员存储为数字,但不存储两个人之间的任何关系。您确实在研究图论,如果可以的话,您应该查看图论的引用书和 Java 库。
那么,什么是信任链接?它是一个有两个人的对象,即受托人和受信任的人。为此创建一个类:
public class Trust {
private final int trustee;
private final int trusted;
public Trust(final int trustee, final int trusted) {
this.trustee = trustee;
this.trusted = trusted;
}
// Getters, equals, hashCode, toString, formatted output for humans.
}
让您的类SocialNetwork
能够创建这些。顺便说一句,在您的主方法中创建一个 SocialNetwork 实例,并停止对其他所有内容使用静态。
public Trust createTrust(Scanner scanner) {
int trustee = scanner.nextInt();
int trusted = scanner.nextInt();
return new Trust(trustee, trusted);
}
您可能需要添加异常处理和文件结尾处理。
创建links
一个Trust
对象列表,然后编写根据需要扫描该列表的方法。
/**
Return a list of all the people who trustee trusts.
@param trustee A person in the system.
@return a list of the people trustee trusts.
*/
public List<Integer> trusting(int trustee) {
final List<Integer> trusted = new ArrayList<>();
for (Trust link: links) {
// Add something from link to trusted if it should.
// This looks like homework; I'm not doing everything for you.
}
return trusted;
}
根据需要编写其他方法。然后,思考这些数据结构对于这个问题是否有效。 map 可以更好吗?来自其他库的 MultiMap
?某种开源图论库?也许您应该使用数据库。也许您应该有一个 Person
类,而不是只使用整数;这样你就可以用名字来标记人们。
关于java - 解释java数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16019020/