Compter le nombre d’occurrence dans un tableau | java
Dans ce tutoriel nous allons découvrir comment compter le nombre d’occurrence dans un tableau en Java.
[wx_adsense]
Exemple:
public class Main {
public static void main(String[] args) {
int [] tab = new int [] {1, 1, 7, 3, 2, 2, 2, 4, 1};
int [] count = new int[100];
/* i : compteur, tmp : stock tmporairement la valeur
à un certain index du tableau tab[]*/
int i,tmp = 0;
/* tmp agira comme une valeur d'index pour le tableau count
et gardera une trace du nombre d'occurrences de chaque nombre*/
for(i = 0; i < tab.length; i++){
tmp = tab[i];
count[tmp]++;
}
for(i=1; i < count.length; i++){
if(count[i] > 0 && count[i] == 1){
System.out.printf("%d se produit %d fois\n",i, count[i]);
}
else if(count[i] >= 2){
System.out.printf("%d se produit %d fois\n",i, count[i]);
}
}
}
}
Sortie:
1 se produit 3 fois 2 se produit 3 fois 3 se produit 1 fois 4 se produit 1 fois 7 se produit 1 fois
[wx_amazon]
