TP 13 exo1: implement odd and even elements counting with callbacks
[TD_C.git] / TP_13 / exo1 / lib / array.c
... / ...
CommitLineData
1#include <stdlib.h>
2#include <stdio.h>
3
4#include "array.h"
5
6int* create_tab(int tab[], unsigned tab_size) {
7 tab = malloc(sizeof(int) * tab_size);
8 if (tab != NULL) {
9 /* initialize to zero the integer array */
10 for (unsigned i = 0; i < tab_size; i++) {
11 tab[i] = 0;
12 }
13 }
14 return tab;
15}
16
17void free_tab(int tab[]) {
18 free(tab);
19}
20
21/* we suppose both tabs are already created */
22static void copy_tab(int src_tab[], int dest_tab[], unsigned src_tab_size, unsigned index_offset) {
23 /* FIXME: I think it's worth doing some sanity checks on the array size:
24 * dest_tab_size >= src_tab_size */
25 if (src_tab == NULL || dest_tab == NULL) {
26 printf("please ensure you have created both arrays beforehand\n");
27 return;
28 }
29 for (unsigned i = 0; i < src_tab_size; i++) {
30 dest_tab[i + index_offset] = src_tab[i];
31 }
32}
33
34/* one must free the two source tabs in case they will be unused after to concatenation */
35int* concat_tab(int tab1[], unsigned tab_size1, int tab2[], unsigned tab_size2) {
36 int* tab_dest = NULL;
37 tab_dest = create_tab(tab_dest, tab_size1 + tab_size2);
38
39 copy_tab(tab1, tab_dest, tab_size1, 0);
40 copy_tab(tab2, tab_dest, tab_size2, tab_size1);
41 return tab_dest;
42}
43
44int* resize_tab(int tab[], unsigned new_tab_size) {
45 tab = realloc(tab, sizeof(int) * new_tab_size);
46 return tab;
47}
48
49/* number of occurences of an element in an unsorted array */
50unsigned count_tab_element(int tab[], unsigned tab_size, int element) {
51 unsigned el_count = 0;
52
53 for (unsigned i = 0; i < tab_size; i++) {
54 if (tab[i] == element) {
55 el_count++;
56 }
57 }
58 return el_count;
59}
60
61unsigned count_tab_criteria(int tab[], unsigned tab_size, count_criteria_cb c_criteria) {
62 unsigned cr_count = 0;
63
64 for (unsigned i = 0; i < tab_size; i++) {
65 if (c_criteria(tab[i])) {
66 cr_count++;
67 }
68 }
69 return cr_count;
70}
71
72bool is_even(int a) {
73 return (a % 2 == 0);
74}
75
76bool is_odd(int a) {
77 return (a % 2 != 0);
78
79}
80
81void sort_tab(int tab[], unsigned tab_size, criteria_cb criteria) {
82 sort_bubble_array(tab, tab_size, criteria);
83}