Renaming bfs to solver. Adding fclose so the file doesn't remain open after use. Finally creating min2 and min3 functions.
This commit is contained in:
5 files changed
+48
-14
No files matched your search
+88
@@ -0,0 +1,88 @@
|
||||
#include "solve.h"
|
||||
#include "node.h"
|
||||
#include "queue.h"
|
||||
#include "io.h"
|
||||
#include "maths.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
bool bfs(int128_t* sum, int128_t a0, int128_t b0, int128_t c0, int print_mode) {
|
||||
node_pool_reset();
|
||||
queue_clear();
|
||||
clear_hash_table();
|
||||
|
||||
Node* root = node_pool_alloc();
|
||||
if (!root) return false;
|
||||
|
||||
root->a = a0; root->b = b0; root->c = c0;
|
||||
root->move = '\0'; root->parent = NULL;
|
||||
|
||||
queue_push(root);
|
||||
visit_and_mark(a0, b0, c0);
|
||||
|
||||
Node* found = NULL;
|
||||
while (queue_size() > 0) {
|
||||
Node* curr = queue_pop();
|
||||
|
||||
/* Goal Check */
|
||||
if (curr->a == 0 || curr->b == 0 || curr->c == 0) {
|
||||
found = curr;
|
||||
break;
|
||||
}
|
||||
|
||||
try_push_children(curr);
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
if (print_mode == 1) printf("No solution found.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
int32_t max_moves = 0;
|
||||
for (Node* p = found; p && p->move != '\0'; p = p->parent) max_moves++;
|
||||
|
||||
char* moves;
|
||||
if (print_mode == 1) {
|
||||
moves = malloc(max_moves + 1);
|
||||
if (!moves) { fprintf(stderr, "Out of memory\n"); return false; }
|
||||
moves[max_moves] = '\0';
|
||||
|
||||
Node* p = found;
|
||||
int32_t idx = max_moves - 1;
|
||||
while (p && p->move != '\0') {
|
||||
moves[idx--] = p->move;
|
||||
p = p->parent;
|
||||
}
|
||||
|
||||
printf("\nSolution found!\n");
|
||||
printf("Initial: (");
|
||||
print_int128(a0); printf(", ");
|
||||
print_int128(b0); printf(", ");
|
||||
print_int128(c0); printf(")\n");
|
||||
|
||||
printf("Final: (");
|
||||
print_int128(found->a); printf(", ");
|
||||
print_int128(found->b); printf(", ");
|
||||
print_int128(found->c); printf(")\n");
|
||||
|
||||
printf("Moves (%i): %s\n", max_moves, moves);
|
||||
} else if (print_mode == 2) {
|
||||
print_int128(c0);
|
||||
printf(" the required amount of moves is: %i\n", max_moves);
|
||||
}
|
||||
*sum+=max_moves;
|
||||
|
||||
if (print_mode == 1) {
|
||||
free(moves);
|
||||
moves = NULL;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool solve(int128_t* sum, int128_t a0, int128_t b0, int128_t c0, int print_mode) {
|
||||
/* Find a better way */
|
||||
|
||||
/* Fallback to BFS */
|
||||
return bfs(sum, a0, b0, c0, print_mode);
|
||||
}
|
||||
Reference in new issue
Block a user