Click here to Skip to main content
15,616,869 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The method public static int[][] quantities(int[] array) is to count the number of occurrences of each number occurring in the array. The number #x of occurrences of the number x is to be represented by the array {x, #x}. The method now returns an array of such arrays. For each number occurring in the array, such an entry is to be created in the order in which the numbers in the array occur for the first time.

Here is an example: The array
ex1 = [1, 1, 2, 1, 3, 2, 1]

contains 4 times the 1, 2 times the 2 and 1 time the 3, which is represented by the arrays {1, 4}, {2, 2} and {3, 1}. The first occurrence of 1 precedes the first occurrence of 2, which in turn precedes the first occurrence of 3. The return value of quantities(ex1) is therefore
  [1, 4],
  [2, 2],
  [3, 1]

Here is another example: For the array
ex2 = [2, 0, 3, 0, 2, 5, 5, 3, 2, 0, 0, 0]

the return value of quantities(ex2) would be
  [2, 3],
  [0, 5],
  [3, 2],
  [5, 2]

What I have tried:

As of now i dont have any idea how to do it. Any help would really be appreciated
Updated 13-Nov-22 4:44am

1 solution

Think about how you would do it manually: you would create a blank sheet of paper and look at each number in turn.
If it is not on the piece of paper, add a line with the number and a count of 1.
Otherwise, increment the count for that number by 1.

When you have looked at all the numbers, the sheet of paper contains the information you need in the order you need them.

That's what you need to do in code as well, but using arrays instead of a sheet of paper.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900