-1

I am trying to make a counter with a list of 10 elements in random position, the problem is that after making the complete tour of my array I must print on the screen how many numbers that are repeated.

To do this, I made the method out of my Main space, I declared the array and the "for loop" to tour my array, the question is after that I must will include in the same method the counter ? ...

public static int Vectores(int a[]) {
    // Declared variable
    a = new int[10];
    int lf = a.length;

    // Here we will tour the array and then complete the arrays with random numbers.
    for (int i = 0; i < lf; i++) {
        a[i] = (int) (Math.random() * 100);
        System.out.println(" A:" + a[i] );
    }
    return a[i];

    // Here will be an "if condition" + and for loop to the counter 
    int counter = 0;
    for (int i = 0; i < 10; i++) {
    }
} // END
Robert
  • 7,394
  • 40
  • 45
  • 64
Mati
  • 63
  • 6
  • https://stackoverflow.com/questions/31738717/java-count-duplicates-from-int-array-without-using-any-collection-or-another-i – OldProgrammer Oct 26 '19 at 15:05

1 Answers1

0

Your method is taking an array as param, which is being assigned with a new array and the array itself not return. If the random values have to be generated in the method and only the number of repetitions needed, the parameter is not needed! And you also have a return statement after your first loop, making the rest of the code unreachable!

This being said, you could track the repetitions as follow:

...
int a[] = new int[10];
Map<Integer, Integer> count = new HashMap<>();

for (int i = 0; i < a.length; i++) {
    a[i] = (int) (Math.random() * 10);
    count.compute(a[i], (k, ov) -> ov != null ? ++ov : 1);
}

List<Entry<Integer, Integer>> repetitions = count.entrySet().stream()
                                             .filter(e -> e.getValue() > 1)
                                             .collect(Collectors.toList());

// Return the value & or display the details
if (repetitions.isEmpty()) {
    System.out.println("No repetition found !");
} else {
    System.out.println("Number of value which are repeated : " + repetitions.size());
    repetitions.forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue() + " times"));
}
...

Sample run

Cheers!

Abs
  • 300
  • 1
  • 10