Java – Exam – Couples Frequency

In the last java articles I have solved (or commented) the exam problems, given at the Java exam at the SoftUni. I have started with the easiest tasks (in my opinion) and I have gradually came to the toughest ones. The today’s problem is definitely not an easy one and it includes HashMaps and HashSets in its solution.

JavaHashSet

The problem – as an input we have a string with some numbers, divided by spaces. The output should be a summary of the frequencies of all couples of the consecutive numbers. Or with other words this is the input and the output:

Input

5 10 5 10 10 5 5 10 5 10 10 5

Output

5 10 -> 36.36%
10 5 -> 36.36%
10 10 -> 18.18%
5 5 -> 9.09%

So, in this article I will simply comment how to resolve the issue and then I will share the original solution of the problem. Here it goes:

 

  • The first few lines are trivial – we read the line as a string and we create an int array from it, splitted by space.
  • Now the interesting part – first we initialize a HashMap named count with string key and integer value.
  • In a for loop we perform a few actions:
    • We initialize 2 ints = and we give them values from the array nums;
    • We unite them with a space into a string key;
    • We initialize an integer count, which counts the occurences of the couples.
  • Once we have these frequencies, we calculate them into percentages and print them (easily said than done)
  • We use a HashSet and a for loop.
    • There we use the same way the ints firstsecond and the string key;
    • The interesting part of the solution is that after the printing we add the string key to the HashSet and we set a check before the printing whether we have it or not. Thus, a couple is printed just once.
    • The frequency is determined using the key of the HashMap count and dividing it into the number of couples. The number of couples is the array length minus one (e.g. if we have 7 units in the array, these form 6 couples)
    • We use some sophisticated skills to print (or at least they look so to me, I am a VBA programmer after all 🙂 )
  • That is all!

Yup! This task is definitely not for beginners in programming and you should have some 4-10 hours experience (best case scenario!) with HashSet and HashMap in order to solve it.

Enjoy the code:

 

Tagged with: , , ,