TP 13 exo1: Implement a FIXME on array dynamic resizing
[TD_C.git] / TP_13 / exo1 / lib / array.c
CommitLineData
e4001676 1#include <stdlib.h>
475ee86d 2#include <stdio.h>
e4001676 3
884e9557 4#include "array.h"
e4001676 5
34f864c6
JB
6int* create_tab(int tab[], unsigned tab_size) {
7 tab = malloc(sizeof(int) * tab_size);
34dd19e9 8 if (tab != NULL) {
34f864c6
JB
9 /* initialize to zero the integer array */
10 for (unsigned i = 0; i < tab_size; i++) {
11 tab[i] = 0;
12 }
e4001676 13 }
34dd19e9 14 return tab;
e4001676
JB
15}
16
17void free_tab(int tab[]) {
18 free(tab);
19}
20
34f864c6
JB
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 */
475ee86d
JB
25 if (src_tab == NULL || dest_tab == NULL) {
26 printf("please ensure you have created both arrays beforehand\n");
27 return;
28 }
34f864c6 29 for (unsigned i = 0; i < src_tab_size; i++) {
e4001676
JB
30 dest_tab[i + index_offset] = src_tab[i];
31 }
32}
33
475ee86d
JB
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);
e4001676
JB
38
39 copy_tab(tab1, tab_dest, tab_size1, 0);
40 copy_tab(tab2, tab_dest, tab_size2, tab_size1);
475ee86d 41 return tab_dest;
e4001676
JB
42}
43
59941dc1 44int* resize_tab(int tab[], unsigned old_tab_size, unsigned new_tab_size) {
34f864c6 45 tab = realloc(tab, sizeof(int) * new_tab_size);
ac5c12a4 46 /* zero by default the added cells */
59941dc1
JB
47 if (old_tab_size < new_tab_size) {
48 for (unsigned i = old_tab_size; i < new_tab_size; i++) {
49 tab[i] = 0;
50 }
51 }
34dd19e9 52 return tab;
e4001676
JB
53}
54
55/* number of occurences of an element in an unsorted array */
889d5862 56unsigned count_tab_element(int tab[], unsigned tab_size, int element) {
e4001676 57 unsigned el_count = 0;
889d5862 58
e4001676
JB
59 for (unsigned i = 0; i < tab_size; i++) {
60 if (tab[i] == element) {
61 el_count++;
62 }
63 }
64 return el_count;
65}
66
210f7f05 67unsigned count_tab_criteria(int tab[], unsigned tab_size, c_criteria_cb c_criteria) {
889d5862
JB
68 unsigned cr_count = 0;
69
70 for (unsigned i = 0; i < tab_size; i++) {
71 if (c_criteria(tab[i])) {
72 cr_count++;
73 }
74 }
75 return cr_count;
76}
77
78bool is_even(int a) {
79 return (a % 2 == 0);
80}
81
82bool is_odd(int a) {
83 return (a % 2 != 0);
84
85}
86
210f7f05
JB
87void sort_tab(int tab[], unsigned tab_size, s_criteria_cb sort_criteria) {
88 sort_bubble_array(tab, tab_size, sort_criteria);
e4001676 89}