I have completed a red black tree in c and i find it hard to print it in level-order. I have a print-inorder but i cant imagine how am i supposed to display it as a tree in the console print. Is it feasible? Can we implement BFS or DFS here? i've found an algorithm in wiki but i cant apply it.
If anyone has code for it in C could you post it here so i can study it?
from wiki:
levelorder(root)
q = empty queue
q.enqueue(root)
while not q.empty do
node := q.dequeue()
visit(node)
if node.left ā null
q.enqueue(node.left)
if node.right ā null
q.enqueue(node.right)
You can do a BFS, but it might be easier to do an iterative deepening search, since that will save you the trouble of implementing a FIFO queue in C. Pseudocode:
algorithm iterative-deepening(root)
D = max-depth(root)
for d=0 to D
depth-limited-search(root, d)
/* variant of DFS */
algorithm depth-limited-search(node, d)
if node != NULL
if d == 0
print node.contents
else
depth-limited-search(node.left, d - 1)
depth-limited-search(node.right, d - 1)
Related
This question already has answers here:
C How to "draw" a Binary Tree to the console [closed]
(10 answers)
Closed 3 years ago.
I know how to code a binary search tree, and to traverse it in inorder, preorder or postorder fashion.
But, I want to know how I can know where the actual node is:
For example let's say we have the values: 70 90 50 60 80 40
So the root would be 70, 90 to its right, 50 to its left, 60 to 50's right and so on.
So if I were to print this inorder, it would be 40 50 60 70 80 90, increasing order pretty much.
I do this by doing this in the recursive traverse function:
traverse(root->left);
printf("%d ", root->data);
traverse(root->right);
But this doesn't let me know (as far as I know) where the node currently is.
Is there a way to print the tree like this?:
70
50 (70 L) 90 (70 R) // We know which parent the node is from and we know if it's the left or the right of it.
40 (50 L) 60 (50 R) 80 (90 L)
and so on.. if the tree is bigger.
I don't really know how I'd do it. Would I need to link them to their parents? But how would I know the right-left thing if I do just that? Or do I need to print the child when the iterator is on the parent still. Thank you in advance.
Edit: I looked up printing the tree by traversing level by level but I don't think I get to know the parent and the side of the node.. I am trying to implement some codes to c code and I always get crashes.
Seems you want to print the tree level by level, i.e.
level 0: node0
level 1: node1 (node0 L) node2 (node0 R)
level 2: ...
So you need a way to track the current level and the target level (i.e. the one you want to print). Also you need a way to track when there is "no more levels" (i.e. no more to print).
That can be done in many ways. The pseudo code below should give you an idea of one way to do it. It's not the most efficient way but it's pretty simple.
Something like:
bool btPrintLevel(node* root, int targetlevel, int currentlevel)
{
if (targetlevel == currentlevel) return false; // no need to go further down in levels
bool result = false;
result |= btPrintLevel(root->left, targetlevel, currentlevel + 1);
// psedo code
if ((currentlevel + 1 == targetlevel)
{
if (childern_exists)
{
printChildern(...)
result = true;
}
}
result |= btPrintLevel(root->right, targetlevel, currentlevel + 1);
return result;
}
Called like:
int level = 0;
while(btPrintLevel(head, level)) ++level;
This How to print elements from Binary Tree by level in c may also help. It doesn't do exactly what you want but with minor modifications you can achieve your goal.
Recursive algorithms are fine for depth-first traversing of trees, but less suitable for broadth-first. The latter can be done pretty efficiently using a FIFO (pseudo code):
push(fifo, { root, 0 });
while(!isEmpty(fifo))
{
node* n = pop(fifo);
print(n);
if(n->left)
push(fifo, { n->left, 'L' });
if(n->right)
push(fifo, { n->right, 'R'});
}
I've foreseen an additional field designating being left or right child of parent. If you your nodes have a link to their parent, you can instead decide upon n->parent->left == n ? 'L' : 'R'.
Leaving implementing the FIFO up to you (you'll find quite a number of questions here on SO about)...
I am studying for my AI examination, and I am stuck in the Breath first search algorithm. According to the Breath first search algorithm, suppose a robot want to navigate from B to P on the following diagram.
I am suffering on finding the traversal using BFS and DFS.
Consider this matter may much appreciated.
I drew the diagram
I'm not quite sure what the actual question is, but here's some code I wrote to navigate a binary tree breadth-first:
# Print tree breadth-first
def breadthFirst(node):
stack = [[node]]
while len(stack[-1]) != 0:
newLevel = []
for node in stack[-1]:
if node.left != None:
newLevel.append(node.left)
if node.right != None:
newLevel.append(node.right)
if len(newLevel) == 0:
print('\n'.join('\n'.join(n.val for n in level) for level in stack))
stack.append(newLevel)
I have a problem with too deep recursion in c (I'm using Codeblocks). Around recursion depth of 73000 the message Segmentation fault (core dumped) is occurring. The deepest possible recursion depth is size*size (look at code for size). In my case size=500, so deepest possible recursion is 250000. The function that is run recursively is written below:
void sosedi(int *h, int spin, int k, int l, int rec, gsl_rng * r1){
rec+=1;
if(rec>70000) printf("%d\n",rec);
double tc=2.269185;
double temp = tc*0.5;
*(h+k*size+l)=-*(h+k*size+l);
if(k!=size-2 && *(h+(k+1)*size+l)==spin && pow(2.71828182845904523536, -2*J/temp) < gsl_rng_uniform (r1) ){
sosedi(h,spin,k+1,l,rec,r1);
}
if(k!=1 && *(h+(k-1)*size+l)==spin && pow(2.71828182845904523536, -2*J/temp) < gsl_rng_uniform (r1) ){
sosedi(h,spin,k-1,l,rec,r1);
}
if(l!=size-2 && *(h+k*size+l+1)==spin && pow(2.71828182845904523536, -2*J/temp) < gsl_rng_uniform (r1) ){
sosedi(h,spin,k,l+1,rec,r1);
}
if(l!=1 && *(h+k*size+l-1)==spin && pow(2.71828182845904523536, -2*J/temp) < gsl_rng_uniform (r1) ){
sosedi(h,spin,k,l-1,rec,r1);
}
}
I have been searching for a solution and have come across two solutions. First is to write
--stack="some big number"
in project -> build options -> linker settings -> other linker options, but it doesn't work.
The other option is to use ulimit -s unlimited. I know how to use it in terminal, but don't know how to use this command in codeblocks.
I am not sure recursion depth is causing this error, but the code works for size = 100 and size=200.
Thanks for help.
You appear to be a victim of stack overflow.
You should revisit your code logic and try to use some alternative to avoid or minimize recursion or use some technique similar to tail recursion which is optimized by many compilers.
You may also want to read How to convert a recursive function to use a stack
Ok, I solved the problem. I used setrlimit function. Here
is a very nice description on how to use it.
I want to know if its possible to modify an existing chess engine in C that works without multi-threading to be able to support multi-threading. I have no experience in this subject and would appreciate some guidance.
EDIT: To be more specific, is there anything I can add to my implementation of negamax to make it multi-thread compatible? :
static double alphaBetaMax(double alpha, double beta, int depthleft, game_t game, bool player)
{
move_t *cur;
move_t *tmp;
double score = 0;
bool did_move = false;
cur = getAllMoves(game, player);
if(cur == NULL) /*/ check mate*/
return -9999999*(player*2-1);
tmp = firstMove;
firstMove = 0;
while (cur != NULL)
{
game_t copy;
if(depthleft<=0 && !isCapture(game, cur)) { /* Quiescence search */
cur = cur->next;
continue;
}
did_move = true;
copyGame(game, ©);
makeMove(©, *cur);
firstMove = NULL;
score = -alphaBetaMax(-beta, -alpha, depthleft - 1, copy, !player);
if(board_count > MAX_BOARDS)
break;
freeGame(copy);
if(score > alpha)
alpha = score;
if (beta <= alpha)
break;
cur = cur->next;
}
firstMove=tmp;
freeMoves();
if(!did_move)
alpha = evaluate(game)*(player*2-1);
return alpha;
}
A fast chess engine relies on two things: Caching the evaluation of positions, and the alpha/beta strategy. Caching positions and making it thread safe and fast is hard. The alpha/beta strategy relies on the seemingly best move being completely evaluated before you start evaluating other moves. This also makes it tough to use multiple threads.
Beginner composer to Mozart: "Can you tell me how to compose a symphony"? Mozart to beginner: "Maybe at your young age you should try something easier first. " Beginner to Mozart: "But you wrote symphonies when you were much younger than I am now. " Mozart to beginner: "True, but I didn't have to ask anyone".
The Alpha-Beta pruning is inherently single-threaded in nature. There's been successful approaches using variations of Dynamic Tree Splitting which basically means searching various branches at the same time. However the likelihood (in a well tuned engine) that next branch will be searched (or beta-cut) does not usually outweigh the other parallelism bottlenecks like memory waits.
I would suggest, first modify your search to a "re-search" algorithm like NegaScout or PVS which with small code changes will give good improvements over your current pure Alpha-Beta, then secondly fine-tune your move ordering to yield efficient beta-cut.
Thereafter you could try to split the tree based on beta-cut chances. Typically there would be higher chance of cutoff when a move is found in the transposition-table or a killer move and lesser chance when starting to search bad captures and quiet moves.
Take a look at CPW for some thoughts on it and the YBWC algorithm.
Young Brothers Wait Concept
I'm currently writing a c++ chess engine and I have made a quite simple but not optimal solution:
First I'm generating all moves in the form of a list of structs
I start n threads which repeatedly grab "jobs" from the list
do their search and write back the result into the struct. When the
list is empty, a thread kills itself.
In the general search function I join the threads and loop through the results afterwards.
Is this approach most efficient?
As currently the focus on searching the most relevant moves first but you'll eventually look at all moves and also hardly get a cutoff at depth one but works fine
Simple to implement and in any case better than a "one-cpu" search. Even if one move takes way more time - it's running on one cpu, like back then :D
Maybe start out with that
I am asked to implement a recursive function for traversing a general tree (first child, next sibling notation) and a binary tree in depth-first order.
The function should print the node when it last visits it. For example, for the tree below, the nodes should be printed in the following order.
I think I have done the function for the binary tree but I could not do the general one:
Here is my code for the binary tree:
void PostOrder(node* root) {
if (root == NULL)
return;
else {
PostOrder(root->left);
PostOrder(root->right);
printf(ā%cā, root->key);
}
}
Can anyone help?
It sounds like it's a typical "general tree represented as binary tree" with two pointers: first child, and next sibling. We can draw the tree as a standard binary tree, with each child having a down-leading arrow and a right-leading arrow.
I think the tree described in your comment looks like this:
a
|
V
b ------------> c
| |
V V
d --> e --> f g
|
V
h --> i
You want, at each node of the tree, to:
Print all the descendants first, by processing the first child (follow the down arrow).
Then print the node's value
Then process the siblings (follow the right arrow).
Applying this to the tree above, we get:
GeneralTreePostOrder(a) ->
GeneralTreePostOrder(b) -> # Follow child pointer
GeneralTreePostOrder(d) -> # Follow child pointer
# No children
print d
GeneralTreePostOrder(e) -> # Follow sibling pointer
# No children
print e
GeneralTreePostOrder(f) -> # Follow sibling pointer
# No children
print f
# No more siblings
print b
GeneralTreePostOrder(c) -> # Follow sibling pointer
Etc., which prints d e f h i g c a.
Writing a new function for the general tree (N.B. printf should use a double-quoted format string):
void GeneralTreePostOrder (node* root) {
if (root == NULL)
return;
else {
GeneralTreePostOrder (root->left); // Process children
printf ("%c", root->key);
GeneralTreePostOrder (root->right); // Process siblings
}
}