opti rechercher_par_id

This commit is contained in:
2026-10-21 11:21:16 +02:00
parent 8b28803301
commit e9c7b77dee
2 changed files with 29 additions and 5 deletions
+16 -5
View File
@@ -148,12 +148,21 @@ long meilleure_periode(const long *totaux, int nb_jours, int *debut, int *fin)
}
/* F6 : retrouve une transaction à partir de son id */
const Transaction *rechercher_par_id(const Transaction *t, int n, int id)
const Transaction *rechercher_par_id(const Transaction *const *index, int n, int id)
{
if (id < 0 || id >= n)
return NULL;
return index[id];
}
static const Transaction **construire_index(const Transaction *t, int n)
{
const Transaction **index = malloc((size_t)n * sizeof(*index));
if (index == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
if (t[i].id == id)
return &t[i];
return NULL;
index[t[i].id] = &t[i];
return index;
}
/* F7 : nombre de paires de transactions de montants opposés (a + b = 0) */
@@ -259,12 +268,14 @@ int main(void)
/* recherches par id, dans l'ordre d'origine */
long somme_requetes = 0;
unsigned long etat = 12345;
const Transaction **index = construire_index(t, NB_TRANSACTIONS);
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(index, NB_TRANSACTIONS, (int)((etat >> 8) % NB_TRANSACTIONS));
if (r != NULL)
somme_requetes += r->montant;
}
free(index);
int nb_clients = nb_clients_distincts(t, NB_TRANSACTIONS);