exo 4 fin du tp generecite
This commit is contained in:
31
DEV.3.2/TP/TP1-Generecite/Association.java
Normal file
31
DEV.3.2/TP/TP1-Generecite/Association.java
Normal file
@@ -0,0 +1,31 @@
|
||||
public class Association<E> {
|
||||
private E element;
|
||||
private int frequence;
|
||||
|
||||
public Association(E element, int frequence) {
|
||||
this.element = element;
|
||||
this.frequence = frequence;
|
||||
}
|
||||
|
||||
public E getElement() {
|
||||
return element;
|
||||
}
|
||||
|
||||
public void setElement(E elt) {
|
||||
this.element = elt;
|
||||
}
|
||||
|
||||
public int getFrequence() {
|
||||
return frequence;
|
||||
}
|
||||
|
||||
public void setFrequence(int f) {
|
||||
this.frequence = f;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Association [element=" + element + ", frequence=" + frequence + "]";
|
||||
}
|
||||
}
|
||||
34
DEV.3.2/TP/TP1-Generecite/Main.java
Normal file
34
DEV.3.2/TP/TP1-Generecite/Main.java
Normal file
@@ -0,0 +1,34 @@
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
|
||||
public class Main {
|
||||
|
||||
public static <T> Association<T> elementPlusFrequent(T[] tab) {
|
||||
java.util.Map<T, Integer> compteur = new java.util.HashMap<>();
|
||||
|
||||
for (T elem : tab) {
|
||||
compteur.put(elem, compteur.getOrDefault(elem, 0) + 1);
|
||||
}
|
||||
|
||||
T resultat = null;
|
||||
int maxFreq = 0;
|
||||
for (T elem : tab) {
|
||||
int freq = compteur.get(elem);
|
||||
if (freq > maxFreq) {
|
||||
maxFreq = freq;
|
||||
resultat = elem;
|
||||
}
|
||||
}
|
||||
|
||||
return new Association<>(resultat, maxFreq);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String[] mots = {"chat", "chien", "chat", "oiseau", "chien", "chat"};
|
||||
System.out.println(elementPlusFrequent(mots));
|
||||
|
||||
Integer[] nombres = {1, 2, 2, 3, 1, 2};
|
||||
System.out.println(elementPlusFrequent(nombres));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user