Karan Sharma
Karan Sharma

Reputation: 2599

Is there a data structure to do the following:

When I input a certain data item (character here), I can access the elements it relates to like:

When I input 'A', it gives me access to the values (2, 3, 4, 5), e.g.:

A - 2,3,4,5   
B - 6,7,9  
C - 10, 11, 12, 13  
D - 1,8
and so on...

Also that A, B, C, D could be any data item, int or even a string.

What I am thinking is, I can hold on a linear array and then each item in the array be the header for a linked list. Is this a correct and optimal solution to the above data structure required? Do we already have some data structure to do this?

Upvotes: 0

Views: 74

Answers (2)

Julien Bourdon
Julien Bourdon

Reputation: 1723

The best solution is to use a Hash Table with an array (or list) in the table value.

Here an example in Java using HashMap

Map<String,Integer[]> theMap;
theMap = new HashMap<String,Integer[]>();
theMap.put("A",{2,3,4,5});
theMap.put("B",{6,7,9});
theMap.put("C",{10,11,12,13});
theMap.put("D",{1,8});

/* Access Values */
int two = theMap.get("A")[0];

You could also use ArrayList instead of arrays for your integers.

The code would become as follows:

ArrayList<Integer> listA = new ArrayList<Integer>();
    listA.add(2);
    listA.add(3);
    listA.add(4);
    listA.add(4);

ArrayList<Integer> listB = new ArrayList<String>();
    listB.add(6);
    listB.add(7);
    listB.add(9);

ArrayList<Integer> listC = new ArrayList<Integer>();
    listC.add(10);
    listC.add(11);
    listC.add(12);
    listC.add(13);

ArrayList<Integer> listD = new ArrayList<Integer>();
    listD.add(1);
    listD.add(18);

    Map<String,List<Integer>> theMap;
    theMap = new HashMap<String,List<Integer>>();
    theMap.put("A",listA);
    theMap.put("B",listB);
    theMap.put("C",listC);
    theMap.put("D",listD);

    /* Access Values */
    int two = theMap.get("A").get(0);

Upvotes: 1

phihag
phihag

Reputation: 287785

Use a simple dictionary/map/associative array whose elements are lists (or sets). In Python, a collections.defaultdict can help here:

import collections
d = collections.defaultdict(list)
A,B,C,D = ['A', 8, 3.0, (1,2)]
d[A].extend([2, 3, 4])
d[A].append(5)
# d[A] is now [2,3,4,5]

Upvotes: 0

Related Questions