-2

Scenario: You have been supplied with an ascii text file containing one day’s worth of catch records. Each line in the file contains one "colon separated" catch record with three fields:

CONTESTANTS_NAME:FISH_TYPE:FISH_WEIGHT

for example

PETER:TUNNY:13.3

which indicates that a competitor called PETER caught a TUNNY weighing 13.3 kg. Note that PETER may have caught more than one fish on the day.

How would you solve this problem using java's built-in classes Tokenizer and HashMap?

Your design should provide the following analysis:

  1. The total weight of each type of fish caught on the day.
  2. The total weight of fish caught by each competitor.
  3. The top three competitors ranked by total catch weight.

Reason I'm posting this is that at first glance I sort of panicked knowing that any map contains just a key-value pair and had no idea how to solve this since it has three fields. What I did is have two HashMaps, first one had keys with CONTESTANT-NAME and second one keys were FISH_NAME and was able to provide the required analysis: this required a number of loops and I'm not sure if that's a good way of programming. If somebody has a better approach, please let me know. I just need the logic.

Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134
ac3hole
  • 123
  • 2
  • 10

2 Answers2

1

You may want to check out table class, like Guava Table (think of it as of 2-dimensional map). Then you may use CONTESTANT_NAME as a first key, FISH_NAME as a second, and a weight as a stored value.

Guava Table even pretends to do well with sparse tables, so I strongly suggest you to give it a try.

Alex Abdugafarov
  • 6,112
  • 7
  • 35
  • 59
0

you can do a get/update/put combo on the hashmap

Double contestantTotal = contestantMap.get(contestant);
if(contestantTotal ==null)contestantTotal = Double.getValue(0);//if it wasn't already in the map the returned value will be null
contestantTotal += weight;
contestantMap.put(contestant,contestantTotal );//put overwrites the previous values

Double fishTypeTotal = fishTypeMap.get(fishType);
if(fishTypeTotal ==null)fishTypeTotal = Double.getValue(0);
fishTypeTotal += weight;
fishTypeMap.put(fishType,fishTypeTotal);

this requires just 3 loops one the input loop and 2 output loops

ratchet freak
  • 47,288
  • 5
  • 68
  • 106