move pointer walking to front of loop lol

This commit is contained in:
Daniel Løvbrøtte Olsen 2020-11-25 09:09:08 +01:00
parent d9b05de8b7
commit c1d0fc9d87

View File

@ -21,6 +21,18 @@ struct Node* newNode(void) {
return nNode;
}
void free_all(struct Node* node) {
if (!node) {
return;
};
for (int i = 0; i < 10; i++) {
free_all(node);
};
free(node);
}
int numbers[] = {113, 11354, 77777, 255044};
int main(void) {
@ -31,16 +43,22 @@ int main(void) {
for (int i = 0; i < n_numbers; i++) { // Go through all the phone numbers in the global list
struct Node* pointer = root; // Create a pointer that points to whatever part of the trie we're working on
char number[9]; // A number has 8 + \0 chars
char number[8 + 1]; // A number has 8 + \0 chars
snprintf(number, 9, "%i", numbers[i]); // Convert int to string
int len_number = strlen(number);
for (int j = 0; j < len_number - 1; j++) { // loop over chars in the phone number
for (int j = 0; j < len_number; j++) { // loop over chars in the phone number
int index = number[j] - '0'; // Go to the node we're testing
if (pointer->children[index == NULL]) {
pointer->children[index] = newNode();
};
pointer = pointer->children[index];
if (j == len_number - 1) { // if we are at the last iteration
if (pointer->isEnd == true) { // Check if we've seen the number before
printf("Duplicate Number found at element %i, number %s", i, number);
break;
}
else { // if we're at the last iteration, and isEnd isnt true, its either a new number OR we found a prefix
};
// if we're at the last iteration, and isEnd isnt true, its either a new number OR we found a prefix
bool continues = false;
for (int k = 0; k < 10; k++) {
if( pointer->children[k] != NULL) {
@ -50,31 +68,28 @@ int main(void) {
if (continues == true) {
printf("FOUND PREFIX IN NUMBER\n");
printf("%s and %s", number, number);
while (pointer->isEnd != true) { // follow the first paths you can find
while (pointer->isEnd != true) { // follow the first path you can find
for (int k = 0; k < 10; k++) {
if( pointer->children[k] != NULL) {
pointer = pointer->children[k];
printf("%c", k + '0');
printf("%c", k + '0'); // Print the path as we go
break;
};
};
};
printf("\n");
return 0;
};
free_all(root); // Clean up
return 0; // return true or success or whatever
};
pointer->isEnd = true;
}
};
else if (pointer->isEnd == true) { // if we've already seen a shorter number with this prefix
printf("Found prefix!");
printf("Found prefix!\n");
for (int k = 0; k < j; k++) {
printf("%c", number[k]);
}
printf("\n");
};
int index = number[j+1] - '0';
pointer->children[index] = newNode();
pointer = pointer->children[index];
};
};
}