Jamess11
Jamess11

Reputation: 174

How to keep track of number of occurrences between two dependent LinkedLists?

I'm having some trouble figuring out how to keep track of occurrences between two dependent LinkedLists.

Let me elaborate with an example:

These are the linked lists in question.

They are dependent because each value in first list corresponds to the value in the second list with the same index i. Both lists are always the same length.

{sunny, sunny, rainy, sunny, cloudy, sunny, ...}
{yes, no, no, maybe, yes, no, ...}

What I need is to somehow keep track of the "pairs" of occurrences. For example:

sunny -> 1 yes, 1 maybe, 2 no
rainy -> 1 no
cloudy -> 1 yes

Note: There doesn't have to be exactly 3 options. There can be more or less. Also the names of the items of the lists aren't known previously.

So yea, I'm wondering which is the best way to go about storing this information as I've hit a dead end.

Any help is appreciated.

Upvotes: 1

Views: 63

Answers (1)

Matteo NNZ
Matteo NNZ

Reputation: 12665

You may do that with a Map<String, Map<String, Integer>.

  • The key of the outer map is the weather (sunny, rainy etc.)
  • The value is another map which contains each possible value (yes, no, maybe...) and the number of times that value occurs.

Something like this to merge the two lists:

public static Map<String, Map<String, Integer>> count(List<String> weathers, List<String> answers) {
    //weathers olds the strings 'sunny', 'rainy', 'sunny'...
    //answers old the strings 'yes', 'no'...
    //this code assumes both lists have the same size, you can enforce this in a check or throw if not the case
    Map<String, Map<String, Integer>> merged = new HashMap<>();
    for (int j = 0; j < weathers.size(); j++) {
        if (merged.containsKey(weathers.get(j))) {
            Map<String, Integer> counts = merged.get(weathers.get(j));
            counts.put(answers.get(j), counts.getOrDefault(answers.get(j), 0) + 1);
        } else {
            Map<String, Integer> newAnswer = new HashMap<>();
            newAnswer.put(answer.get(j), 1);     
            merged.put(weathers.get(j), newAnswer);
        }
    }
    return merged;
}

The logic applied to the code above is that you loop through each occurrency of the list(s) and you check if your map already contain that weather.

  • If it's the case, you get the already existing map and increase the number for that answer (if the answer is not present yet, you will start from zero)
  • If it's not the case, you add a new map for that weather where you only have the first answer with count 1.

Sample usage:

Map<String, Map<String, Integer>> resume = count(weathers, answers);
//How many times 'sunny' weather was 'maybe'? 
Integer answer1 = resume.get("sunny").get("maybe");
//How many times 'rainy' weather was 'no'? 
Integer answer2 = resume.get("rainy").get("no");
//etc.

Upvotes: 1

Related Questions