prog_avancee_C/TP1/part_1.c
2024-10-22 13:03:17 +02:00

132 lines
2.6 KiB
C

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#define TAB_SIZE 7
void afficheTab(int tab[], int size);
int* fibonacci(int n);
void print_sizes();
void exercice_4();
int est_permutation(int* tab, int n);
int * permutation(int n);
char * appliquer_permutation(char * T, int * permutation, int n);
int main(int argc, char *argv[])
{
/*int i;
int *tab = fibonacci(TAB_SIZE);
int * tabptr = tab;
afficheTab(tab, TAB_SIZE);
printf("\n\n");
*/
//print_sizes();
//exercice_4();
// int tab[8] = {0, 1, 2, 3, 4, 5, 6, 7};
// printf("%d\n", est_permutation(tab, 8));
/*int * tab = permutation(TAB_SIZE);
afficheTab(tab, TAB_SIZE);
char bliat[TAB_SIZE] = "Bonjour";
char * bliat_perm = appliquer_permutation(bliat, tab, TAB_SIZE);
for (int i=0; i<TAB_SIZE; i++) {
printf("%c", bliat_perm[i]);
}
printf("\n");
free(bliat_perm);
free(tab);*/
return 0;
}
char * appliquer_permutation(char * T, int * permutation, int n) {
int i;
char * result = malloc(sizeof(char)*n);
for (i=0; i<n; i++) {
result[i] = T[permutation[i]];
}
return result;
}
int * permutation(int n) {
int i, x1, x2, tmp;
int * tab = malloc(sizeof(int)*n);
for (i=0; i<n; i++) {
tab[i]=i;
}
srand(time(NULL));
for (i=0; i<n; i++) {
x1 = rand()%n;
x2 = rand()%n;
tmp = tab[x1];
tab[x1] = tab[x2];
tab[x2] = tmp;
}
return tab;
}
int est_permutation(int* tab, int n) {
int i;
int* checked_tab = malloc(sizeof(int)*n);
for (i=0; i<n; i++) {
if(tab[i]<n && checked_tab[tab[i]]==0){
checked_tab[tab[i]]=1;
} else {
return 0;
}
}
free(checked_tab);
return 1;
}
void afficheTab(int * tabptr, int size) {
int i;
if (tabptr==NULL) {
return;
}
for (i=0; i<size; i++) {
printf("%d, ", tabptr[i]);
}
printf("\n");
}
void exercice_4() {
void * Z = malloc(10*4);
int * X = Z;
//afficheTab(X,10);
//afficheTab((int *)((char *)X+8),8);
free(Z);
}
int* fibonacci(int n) {
int i;
int* tab = malloc(sizeof(int)*n);
tab[0] = 0;
tab[1] = 1;
for (i=2; i<n; i++) {
tab[i]= tab[i-2] + tab[i-1];
}
return tab;
}
void print_sizes() {
printf("char : %lu\n", sizeof(char));
printf("int * : %lu\n", sizeof(int *));
printf("int* : %lu\n", sizeof(int*));
printf("void : %lu\n", sizeof(void));
printf("void * : %lu\n", sizeof(void *));
printf("long int : %lu\n", sizeof(long int));
printf("long int * : %lu\n", sizeof(long int *));
}