BUT2/SCR/SCR2/TP06/ex2.c

106 lines
2.2 KiB
C
Raw Normal View History

2023-10-12 16:39:49 +02:00
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
2023-10-23 13:07:05 +02:00
#include <time.h>
#define ELIMINE -1
2023-10-12 16:39:49 +02:00
typedef struct duel{
2023-10-23 13:07:05 +02:00
int* liste;
int debut;
int tailleGroupe;
2023-10-12 16:39:49 +02:00
} duel;
2023-10-23 13:07:05 +02:00
void affichage(int* liste, int capacite){
int i;
for(i=0; i<capacite; i++){
if (liste[i] != ELIMINE){
printf("%d ",liste[i]);
}
}
printf("\n");
}
2023-10-12 16:39:49 +02:00
2023-10-23 13:07:05 +02:00
int* creerListe(int taille){
int* liste = (int*) malloc(taille*sizeof(int));
int i;
for (i=0; i<taille; i++){
liste[i] = (rand()%100);
}
return liste;
2023-10-12 16:39:49 +02:00
}
2023-10-23 13:07:05 +02:00
int plusPetit(int* liste, int debut, int nb){
int plusGrand = -1;
int i;
int participant1 =- 1;
int indiceParticipant1;
for (i=0; i<nb; i++){
if (liste[debut+i] != ELIMINE){
if (participant1 == -1){
participant1 = liste[debut+i];
indiceParticipant1 = i;
}
else{
if (liste[debut+i] > participant1){
return debut + indiceParticipant1;
}
else{
return debut + i;
}
}
2023-10-12 16:39:49 +02:00
}
2023-10-23 13:07:05 +02:00
}
return -1;
2023-10-12 16:39:49 +02:00
}
2023-10-23 13:07:05 +02:00
void *tournois(void *argument) {
duel duo = *((duel*) argument);
2023-10-12 16:39:49 +02:00
int i;
2023-10-23 13:07:05 +02:00
int perdant = plusPetit(duo.liste, duo.debut, duo.tailleGroupe);
duo.liste[perdant] = -1;
return NULL;
}
2023-10-12 16:39:49 +02:00
2023-10-23 13:07:05 +02:00
int puissance2(int n){
int p;
for (p=1; p<n; p*=2){}
if (p==n){
return 1;
2023-10-12 16:39:49 +02:00
}
2023-10-23 13:07:05 +02:00
return 0;
2023-10-12 16:39:49 +02:00
}
int main(int argc, char** argv[]) {
2023-10-23 13:07:05 +02:00
int nbParticipant = argc-1;
int nbDuel = nbParticipant/2;
int* listeParticipant;
2023-10-12 16:39:49 +02:00
2023-10-23 13:07:05 +02:00
assert(puissance2(nbParticipant)==1);
srand(time(NULL));
listeParticipant = creerListe(nbParticipant);
affichage(listeParticipant, nbParticipant);
2023-10-12 16:39:49 +02:00
2023-10-23 13:07:05 +02:00
while (nbDuel>=1){
pthread_t threads[nbDuel];
duel argument[nbDuel];
int i;
for (i=0; i<nbDuel; i++){
argument[i].liste = listeParticipant;
argument[i].debut = i*(nbParticipant/nbDuel);
argument[i].tailleGroupe = nbParticipant/nbDuel;
2023-10-12 16:39:49 +02:00
}
2023-10-23 13:07:05 +02:00
for (i=0; i<nbDuel; i++){
assert( pthread_create(&threads[i], NULL, tournois, &argument[i]) == 0);
}
for (i=0; i<nbDuel; i++){
2023-10-12 16:39:49 +02:00
assert( pthread_join(threads[i], NULL) == 0);
}
2023-10-23 13:07:05 +02:00
affichage(listeParticipant, nbParticipant);
2023-10-12 16:39:49 +02:00
nbDuel /= 2;
}
return EXIT_SUCCESS;
}