This commit is contained in:
2026-10-26 16:46:41 +01:00
parent 7390921cdc
commit 2a9ee49204
+21 -7
View File
@@ -167,13 +167,12 @@ 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]];
}
/* Comparaison de montants pour qsort */
@@ -330,8 +329,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 */
@@ -339,7 +351,8 @@ 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;
}
@@ -406,6 +419,7 @@ int main(void)
printf("Empreinte : %016lx\n", empreinte(rapport));
free(rapport);
free(index);
free(t);
return 0;
}