This commit is contained in:
2026-10-26 16:34:09 +01:00
parent 78abd1dc3b
commit 39d33fd2b6
+22 -9
View File
@@ -167,15 +167,14 @@ long meilleure_periode(const long *totaux, int nb_jours, int *debut, int *fin)
return meilleur;
}
/* F6 : retrouve une transaction à partir de son id */
const Transaction *rechercher_par_id(const Transaction *t, int n, int id)
/* F6 : retrouve une transaction à partir de son id en O(1) */
const Transaction *rechercher_par_id(const Transaction *t, const int *index, int n, int id)
{
for (int i = 0; i < n; i++)
if (t[i].id == id)
return &t[i];
return NULL;
}
if (id < 0 || id >= n)
return NULL;
return &t[index[id]];
}
/* F7 : nombre de paires de transactions de montants opposés (a + b = 0) */
long nb_paires_opposees(const Transaction *t, int n)
{
@@ -272,8 +271,21 @@ unsigned long empreinte(const char *s)
int main(void)
{
Transaction *t = generer_transactions(NB_TRANSACTIONS);
int *index = malloc(NB_TRANSACTIONS * sizeof(int));
char *rapport = malloc(1 << 20);
char ligne[128];
if (t == NULL || index == NULL || rapport == NULL) {
fprintf(stderr, "Erreur d'allocation mémoire.\n");
free(t);
free(index);
free(rapport);
return 1;
}
for (int i = 0; i < NB_TRANSACTIONS; i++)
index[t[i].id] = i;
rapport[0] = '\0';
/* recherches par id, dans l'ordre d'origine */
@@ -281,7 +293,7 @@ int main(void)
unsigned long etat = 12345;
for (int q = 0; q < NB_REQUETES; q++) {
etat = etat * 1103515245UL + 12345UL;
const Transaction *r = rechercher_par_id(t, NB_TRANSACTIONS, (int)((etat >> 8) % NB_TRANSACTIONS));
const Transaction *r = rechercher_par_id(t, index, NB_TRANSACTIONS, (int)((etat >> 8) % NB_TRANSACTIONS));
if (r != NULL)
somme_requetes += r->montant;
}
@@ -348,6 +360,7 @@ int main(void)
printf("Empreinte : %016lx\n", empreinte(rapport));
free(rapport);
free(index);
free(t);
return 0;
}
}