APL/DEV 3.2/TP01/Fréquences/Frequences.java

60 lines
1.8 KiB
Java
Raw Permalink Normal View History

2022-10-07 11:14:09 +02:00
import java.util.Hashtable;
import java.util.Map;
public class Frequences<T> {
public T mostFrequent(T[] tab) {
Hashtable<T, Integer> indexList = new Hashtable<T, Integer>();
for (T element : tab) {
indexList.put(element, indexList.get(element) == null ? 1 : ((Integer)indexList.get(element)) + 1);
}
T element = tab[0];
Integer count = indexList.get(tab[0]);
for(Map.Entry<T, Integer> entry : indexList.entrySet()) {
if (entry.getValue() > count) {
element = entry.getKey();
count = entry.getValue();
}
}
return element;
}
public Liste<T> getFrequences(T[] tab) {
Hashtable<T, Integer> indexList = new Hashtable<T, Integer>();
for (T element : tab) {
indexList.put(element, indexList.get(element) == null ? 1 : ((Integer)indexList.get(element)) + 1);
}
Association<T> lastEntry = null;
boolean first = true;
Liste<T> list = new Liste<T>();
for(Map.Entry<T, Integer> entry : indexList.entrySet()) {
if (first) {
lastEntry = new Association<T>(entry.getKey(), entry.getValue());
list.setFirstElement(lastEntry);
first = false;
} else {
Association<T> newEntry = new Association<T>(entry.getKey(), entry.getValue());
lastEntry.setSuivant(newEntry);
lastEntry = newEntry;
}
}
return list;
}
public static void main(String[] args) {
Frequences<String> f = new Frequences<String>();
String[] tab = {"test", "test", "test", "12", "12", "12", "12"};
System.out.println(f.mostFrequent(tab));
}
}