In: Computer Science
(JAVA)
Repeated
Class diagram:
Repeated
+ repeatedDetector(ArrayList<Integer> a) : int
For this exercise, you will have to implement the class diagram above. Basically, the objective of this exercise is to develop the class and the previous method, in such a way that it tells us the amount of "repeated" elements that are in the dynamic array.
When we speak of "repeated", we mean counting the number of numbers of the same value that are found in succession.
Example 1: The method receives a dynamic array ArrayList <Integer>, which internally has this data: [1,1,4,1,4,1,1]
The method returns 2 (since it found 2 sequences of equal numbers).
Example 2: the method receives a dynamic array ArrayList <Integer>, which internally has this data: [1,1,1,1,1]
The method returns 1 (since it found 1 sequence of equal numbers).
import java.util.*;
class repeat
{
public int repeatDectetor(ArrayList<Integer>a)
{
int c=0;
Map<Integer, Integer> duplicates = new HashMap<Integer, Integer>();
for (int i : a) { //maping the duplicate item in hash table
if (duplicates.containsKey(i)) {
duplicates.put(i, duplicates.get(i) + 1);
} else {
duplicates.put(i, 1);
}
}
for (Map.Entry<Integer, Integer> entry : duplicates.entrySet())
{
if(entry.getValue()>1)//counting the duplicate items
c++;
}
return c;
}
public static void main(String[] args) {
ArrayList<Integer> list=new ArrayList<Integer>();
repeat obj=new repeat();
list.add(1);
list.add(1);
list.add(1);
list.add(4);
list.add(1);
list.add(4);
list.add(1);
list.add(1);
int x=obj.repeatDectetor(list);
System.out.print("number of duplicate element is "+x);
}
}
output:
number of duplicate element is 2