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 120 121 122 123 124 125 126 127 128
| #include <iostream>
#include <list>
#include <map>
class Elt {
public:
Elt() {
indexes_list = NULL;
}
Elt(int first_index) {
indexes_list = new std::list<int>(1, first_index);
}
~Elt() {
if (indexes_list != NULL) {
delete indexes_list;
indexes_list = NULL;
}
}
public:
void add_index(int index) {
// Useless Test: the default constructor is never called
// if (indexes_list != NULL) {
indexes_list->push_front(index);
// } else {
// indexes_list = new std::list<int>(1, index);
// }
}
void print() {
if ((indexes_list == NULL) || (indexes_list->empty())) return;
std::list<int>::iterator it = indexes_list->begin();
std::cout << "occurence: " << indexes_list->size() << std::endl << (*it);
it++;
for (;it != indexes_list->end(); ++it) {
std::cout << " - " << (*it);
}
std::cout << std::endl;
}
private:
std::list<int>* indexes_list;
};
// Type List
// Maybe create a class List
typedef std::map<unsigned char, Elt*> List;
void list_remove_all(List& list) {
if (!list.empty()) {
for(std::map<unsigned char, Elt*>::iterator it = list.begin(); it != list.end(); ++it) {
delete ((Elt*) it->second);
list[it->first] = NULL;
}
list.erase(list.begin(), list.end());
}
}
void algo(int number, List& list) {
list_remove_all(list);
Elt* tmp = NULL;
int nb = number, index = 0;
unsigned char digit = 0;
while(nb >= 10) {
nb = (nb / 10);
index++;
}
index++;
for(;index > 0; index--) {
digit = (number % 10);
number = (number / 10);
std::cout << "Find " << (int) digit << " (" << index << ")" << std::endl;
tmp = list[digit];
if (tmp != NULL) {
tmp->add_index(index);
} else {
list[digit] = new Elt(index);
}
}
}
int main() {
int number = 7377683;
List list;
algo(number, list);
std::cout << std::endl;
for(std::map<unsigned char, Elt*>::iterator it = list.begin(); it != list.end(); ++it) {
std::cout << "Digit: " << (int) it->first << ", ";
((Elt*) it->second)->print();
}
list_remove_all(list);
} |
Partager