Construct chain of links from list

浪尽此生 提交于 2019-12-11 07:34:37

问题


I have a list of key/value pairs and I need to detect chains in the list where the value matches a key.

E.g. from the below there could be 12, 23, 34 or 62, 23, 34

Key  Value
1    2
3    4
2    3
6    2

More than one value can be pointing to the same key but I need to store different 'chains' for each unique start and end point. The list could be in any order.

I'm using Java but am I bit stuck on how to tackle this problem.

Please help!


回答1:


Recursion!

import java.util.HashMap;
import java.util.Map;

public class Chain
{
    private static Map< String , String > map;

    public static void main( String args[] )
    {
        map = new HashMap< String , String >();

        map.put( "1" , "2" );
        map.put( "3" , "4" );
        map.put( "2" , "3" );
        map.put( "6" , "2" );

        for ( String key : map.keySet() )
        {
            System.out.print( "(" + key + "," + map.get( key ) + ")" );
            recurse( map.get( key ) );
            System.out.println();
        }
    }

    private static void recurse( String value )
    {
        if ( map.containsKey( value ) )
        {
            System.out.print( " (" + value + "," + map.get( value ) + ")" );
            recurse( map.get( value ) );
        }
    }
}

Gives you the following output:

(3,4)
(2,3) (3,4)
(1,2) (2,3) (3,4)
(6,2) (2,3) (3,4)



回答2:


Create a Map<Integer, List<Integer>>, store all your pairs in that map, and then iterate the map.

Pseudo-code:

// 1st step
foreach(key, value){
    if(!map.containsKey(key)){
        map.put(key, new ArrayList());
    }
    map.get(key).add(value);
}
// 2nd step
foreach(entry /* of map */){
    if(map.containsKey(entry.value)){
       // print pairs
    }
}

Obviously this is pseudo-code that won't compile but it should get you started




回答3:


Since this looks like homework, I will give you hints to help you solve the problem yourself, rather than giving you a full solution.

  1. For any key in the map, you can get the corresponding value by calling Map.get(key).
  2. You can use any value as a key to get its corresponding value (if there is one).
  3. You can iterate through all keys in the map using Map.getKeys().

If you only want to print out the chains, this should suffice. If you want to store the chains in some different data structure, please give more information.



来源:https://stackoverflow.com/questions/10175933/construct-chain-of-links-from-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!