简体   繁体   English

比较两个具有唯一结果的列表

[英]Compare two lists with unique result

Preview of data to process: 预览要处理的数据:

A
B
C
D
E

A,B
B,C
D,E

First part are nodes (points in software) and the second part (after empty line) are connections between nodes. 第一部分是节点(软件中的点),第二部分(空行之后)是节点之间的连接。

This file is loaded into two ArrayLists, which are separated (nodes and connections). 该文件被加载到两个ArrayList中,这两个ArrayList是分开的(节点和连接)。 All I need to do is merge (if one from nodes are same as in other connections) that connections between them. 我需要做的就是合并(如果节点中的一个与其他连接中的相同),则合并它们之间的连接。

public class ConsoleProcessor implements IntConsoleProcessor {
 List<String> nodeA = new ArrayList<>();
 List<String> nodeB = new ArrayList<>();

  //From ArrayList split original data to two arrays (point A & B)

  private void splitConnections(ArrayList<String> connections){
      for(String str:connections)
      {
          String[] nodes = str.split(",");
          nodeA.add(nodes[0]);
          nodeB.add(nodes[1]);
      }
      //Console print for fast check of results
      System.out.println(nodeA);
      System.out.println(nodeB);
  }

  public void getResults(ArrayList<String> nodes, ArrayList<String> connections){
      splitConnections(connections);
      //need to continue somehow

  }
 }

As result I want to print out to console connections A,B,C (or something like that) and E,D (or D,E). 结果,我想打印到控制台连接A,B,C(或类似名称)和E,D(或D,E)。

Wanted result: 想要的结果:

Connection counter: 2

E,D
C,A,B

Actual result is only printing out nodeA and nodeB from connections 实际结果只是从连接中打印出nodeA和nodeB

[A, B, E]
[B, C, D]

The structure you are referring to is called graph , with vertices (what you call nodes) and edges (what you call connections). 您引用的结构称为graph ,具有顶点(称为节点)和边(称为连接)。

What you are (supposedly) trying to compute is finding all the connected components of the graph. 您(假设)要尝试计算的是查找图的所有连接组件 There are multiple algorithms to implement this but a trivial approach is just by searching for all vertices connected to a specific vertex and create a component accordingly, something like: 有多种算法可以实现此目的,但是一种简单的方法是通过搜索连接到特定顶点的所有顶点并相应地创建一个组件,例如:

for each vertex A in graph
  if A is already visited skip to next
  mark A as visited
  for each edge A,B in graph
    if B is in a connected component 
      add A to the connected component
    else
      create new connected component with A and B

You should also take care of managing single vertex components but it's just to give you the general idea behind the solution. 您还应该注意管理单个顶点组件,但这只是为了向您提供解决方案背后的总体思路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM