1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| #include<stdlib.h>
#include<stdio.h>
// One element of the list
struct elt {
struct elt* next;
int* indexes_list;
unsigned char digit;
int occurrence;
};
void destroy_list(struct elt** list) {
if ((*list) != NULL) {
struct elt* tmp = (*list);
do {
(*list) = tmp->next;
free(tmp->indexes_list);
free(tmp);
tmp = (*list);
} while(tmp != NULL);
}
(*list) = NULL;
}
void algo(int number, struct elt** list) {
destroy_list(list);
struct elt* tmp = NULL;
int* tmp_indexes_list = NULL;
int nb = number, index = 0;
unsigned char digit = 0;
// Find the index max
while(nb >= 10) {
nb = (nb / 10);
index++;
}
index++;
// For each digit in number
for(;index > 0; index--) {
digit = (number % 10);
number = (number / 10);
// Print the digit found and its index
printf("Find %d (%d)\n", digit, index);
tmp = (*list);
// Does the digit found is already in the list?
while((tmp != NULL) && (tmp->digit != digit)) {
tmp = tmp->next;
}
if (tmp != NULL) {
// The digit is in the list: Recopy the list of index [the collection has one more index], add the new index [the current index] and update the occurrence
tmp_indexes_list = (int*) malloc( sizeof(int) * (tmp->occurrence + 1) );
tmp_indexes_list[0] = index;
for(nb = 1; nb <= tmp->occurrence; nb++) {
tmp_indexes_list[nb] = tmp->indexes_list[nb - 1];
}
tmp->occurrence++;
free(tmp->indexes_list);
tmp->indexes_list = tmp_indexes_list;
tmp_indexes_list = NULL;
} else {
// The digit is not in the list: create and init a new element and insert it in the list
tmp = (struct elt*) malloc( sizeof(struct elt) );
tmp->digit = digit;
tmp->occurrence = 1;
tmp->indexes_list = (int*) malloc( sizeof(int) );
tmp->indexes_list[0] = index;
tmp->next = (*list);
(*list) = tmp;
}
}
}
int main() {
int number = 7377683;
struct elt* list = NULL;
// Init the list
algo(number, &list);
struct elt* tmp = list;
int nb = 0;
// Clear the print
printf("\n");
// Print the list
while(tmp != NULL) {
printf("Digit: %d, occurence: %d\n%d", tmp->digit, tmp->occurrence, tmp->indexes_list[0]);
for(nb = 1; nb < tmp->occurrence; nb++) {
printf(" - %d", tmp->indexes_list[nb]);
}
printf("\n");
tmp = tmp->next;
}
// Destroy the list
destroy_list(&list);
return 0;
} |
Partager