1

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!

Joe Doyle
  • 6,363
  • 3
  • 42
  • 45
hello-klol
  • 735
  • 10
  • 20

3 Answers3

0

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

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0

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.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
0

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)
Jonathan Payne
  • 2,223
  • 13
  • 11