我正在使用一个文本文件,其中第一列表示课程,其他列是该课程的先决条件。
CS1 None
CS2 CS1
CS3 CS2
CS4 CS1
CS5 CS3 CS4
CS6 CS2 CS4我想逐行创建每一行的第一个索引的键值,这些值是索引0之后的值。
例如,行CS6 CS2 CS4的关键字(课程)是CS6,它的值(前提条件)是CS2, CS4。
CS6将CS4作为邻居,而CS4将CS2作为邻居。
但我的输出如下所示:
CS1: None, CS1
CS3: CS2, CS3
CS2: CS1, CS2
CS5: CS3, CS5
CS4: CS1, CS4
CS6: CS2, CS6
None:我正在尝试获得如下输出:
CS1:
CS3: CS2
CS2: CS1
CS5: CS3, CS4
CS4: CS1
CS6: CS2, CS4我的构造函数(它给了我错误的输出):
public Graph(String filename) throws FileNotFoundException {
// open the file for scanning
File file = new File(filename);
Scanner in = new Scanner(file);
// create the graph
graph = new HashMap<String, Node>();
// loop over and parse each line in the input file
while (in.hasNextLine()) {
// read and split the line into an array of strings
// where each string is separated by a space.
Node n1;
Node n2;
String line = in.nextLine();
String[] fields = line.split(" ");
// creates new nodes as necessary
if (graph.containsKey(fields[0])) {
n1 = graph.get(fields[0]);
}
else {
n1 = new Node(fields[0]);
graph.put(fields[0], n1);
}
if (graph.containsKey(fields[1])) {
n2 = graph.get(fields[1]);
}
else {
n2 = new Node(fields[1]);
graph.put(fields[1], n2);
}
n1.addNeighbor(n2);
n1.addNeighbor(n1);
}
in.close();
}addNeighbor方法:
/**
* Add a neighbor to this node. Checks if already present, and does not
* duplicate in this case.
*
* @param n: node to add as neighbor.
*/
public void addNeighbor(Node n) {
if(!neighbors.contains(n)) {
neighbors.add(n);
}
}...and我的节点构造函数:
/*
* Neighbors of this node are stored as a list (adjacency list).
*/
private List<Node> neighbors;
/**
* Constructor. Initialized with an empty list of neighbors.
*
* @param name string representing the name associated with the node.
*/
public Node(String name) {
this.name = name;
this.neighbors = new LinkedList<Node>();
}编辑:我想用我的邻居的方法来解决这个问题,我的输出结果是我打印地图的结果。我只是想通过只改变构造函数而不改变其他方法来解决这个问题。
发布于 2015-03-13 09:02:44
1.找到合适的数据结构
您当前的数据结构似乎过于复杂,这可能会导致您在填充它时出错,并在迭代它以进行显示时出错。
最简单
根据您的目标输出,您似乎不希望在您的结构中存在传递依赖关系。您只想输出课程的直接子项(直接依赖项)。
因此,您的数据结构不应该是真正的图形,而是每个课程到其需求列表的映射:
Map<String, List<String>> requirements = new HashMap<>();保持图的思想
如果您需要更复杂的数据,或者如果您确实需要传递依赖关系,那么您可以使用课程图,以及现有课程的字典(以重用对象)。然而,在这种情况下,我建议您的Course类(如果您愿意,也可以是Node类)包含课程的需求(子类),而不是它的邻居类。
// this is the dictionary, the Node objects themselves contain the dependencies
Map<String, Course> courses = new HashMap<>();
// your Node class (I renamed to make the purpose of the objects more readable)
class Course {
private List<Course> requirements = new LinkedList<>();
public Course(String name) {
this.name = name;
}
public void addRequirement(Course n) {
requirements.add(n);
}
public List<Course> getRequirements() {
return requirements;
}
}2.解决你的问题
您当前并没有每次都阅读整行内容。在获得行的第一个元素后,您应该循环其他元素以将它们添加为需求。
在这里,您只读取数组的索引0和1,这应该会告诉您忘记了潜在的其他需求。
此外,这里还存在一些问题:
n1.addNeighbor(n2); // why is the 1st requirement a neighbour of his parent?
n1.addNeighbor(n1); // why is the parent a neighbour of himself ?https://stackoverflow.com/questions/29022856
复制相似问题