1

The method is called loadArray(), and this method will load an array with a specified number of random values and update the subscripts in the array to reflect the number of times a random number was generated. The values will be between (0, values.length-1). The signature is public static void loadArray(int[] values, int times).

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Vishnu R.
  • 21
  • 1

1 Answers1

1

Well, as you commented, essentially you want a function to count how many times a value appears in a array and, after, updates the array (respective element) with the apearing countings.

In others words you want to update the values with their respective "frequency" that appears in the array.

To to do this I suggest to you a approach using the Map structure.

How does it work, then?

Excluding the array generation step (thinking only in counting step) we can imagine just put each value of the passed array into a map just checking if the value was previously inserted or not.

Then, maps are structures that can holds some information while associate that information to a key, this is the known format "key/value".

Implementation

Ok, to implement this, lets consider a method that generates a array with random numbers, counts it and, after, returns a updated array as we need:

public static int[] count(int arrayLength, int rangeOfRandom) {
    //generates the randons
    Random generator = new Random();
    int[] array = new int[arrayLength];
    for (int i = 0; i < array.length; i++) {
        array[i] = generator.nextInt(rangeOfRandom);
    }

    System.out.println("The generated array was: " +
            Arrays.toString(array));

    //counts each value
    HashMap<Integer, Integer> aux = new HashMap<>();
    for (int i = 0; i < array.length; i++) {
        //if the map DOES NOT contains the current array value
        if (!aux.containsKey(array[i])){
            aux.put(array[i], 1); //puts it with "1 counter"
        } else {
            //if not...
            //...overrides the existing value with itself PLUS 1
            aux.put(array[i], aux.get(array[i]) + 1);
        }
    }

    //updates the array
    int[] nArray = new int[array.length];
    for (int key : aux.keySet()){
        for (int i = 0; i < array.length; i++) {
            if (array[i] == key){
                nArray[i] = array[i] + aux.get(key);
            }
        }
    }

    //here we return the updated array
    return nArray;
}

By doing

System.out.println("The result array is: " +
            Arrays.toString(count(5, 10)));

You get a output like this:

The generated array is: [0, 6, 6, 8, 7]
The result array is: [1, 8, 8, 9, 8]

As you can see, these operations are very elementar, and you can easly refactor it to receive/return other king of parameter and/or types.

For a related discussion, you can check this question.

Obs.: the method I posted is not optimized, it is only for didatic use.

Lucas Sousa
  • 192
  • 3
  • 14