Merge two binary trees in C - c

I am trying to merge two binary trees and this is what I have come up with. I believe that my Insertmerge functions are correct as well as my and merge functions work...I am having trouble with my merge helper. I need to do is post order, left then right, but I am not sure if what I am doing makes sense. Any thoughts?
SparseNode * mergehelper(SparseNode* C_array_1, SparseNode * array_2)
{
if(array_2 ==NULL)
{
return(C_array_1);
}
C_array_1= SparseArray_InsertMerge(C_array_1, ((array_2->left)->index),((array_2->left)-
>value));
C_array_1= SparseArray_InsertMerge(C_array_1, ((array_2->right)->index),((array_2->right)->value));
}
SparseNode* SparseArray_InsertMerge(SparseNode * array, int index, int value)
{
check(array);
if(array ==NULL)
{
return SparseNode_create(index, value);
}
if((array->index)==index)
{
if(array->value == -value)
array= SparseArray_remove (array, array->index);
else
array->value += value;
check(array);
return array;
}
if((array->index)>index)
{
array->left = SparseArray_insert(array->left, index, value);
}
if((array->index)<index)
{
array->right = SparseArray_insert(array->right, index, value);
}
check(array);
return array;
}
/*
post order traversal
new insert for merge
adapt for nonoverwriting
do a tree traversal
then add the node into the copied list in the work of the tree traversal
in merge. copy array1. call mergehelper with copy.
in helper. if null return, then insert left and insert right. print function is similiar
*/
SparseNode * SparseArray_merge(SparseNode * array_1, SparseNode * array_2)
{
SparseNode*Arr1_copy = copy(array_1);
Arr1_copy = mergehelper(Arr1_copy, array_2);
return (Arr1_copy);
}

The easiest way to merge two binary trees is to simply use the functionality that the trees already provide:
a traversal, extracting the values.
a means of inserting values.
So the solution then becomes (pseudo-code):
def mergeTrees (tree1, tree2):
valuePtr = tree2.getFirst();
while valuePtr != NULL:
tree1.addNode (valuePtr->value)
valuePtr = tree2.getNextAfter (valuePtr)
Following that, tree1 will then be a merge of the two trees and you can do what you want with tree2.
Now that's the basic idea - you may want to handle things like duplicate removal or error conditions, but it should be a good enough start to get you going. There's often little point in using the internals of a data structure when the published interface gives you a cleaner way.

Related

Fastest Permutation algorithms for unique permutations using smallest memory [duplicate]

For example, string "AAABBB" will have permutations:
"ABAABB",
"BBAABA",
"ABABAB",
etc
What's a good algorithm for generating the permutations? (And what's its time complexity?)
For a multiset, you can solve recursively by position (JavaScript code):
function f(multiset,counters,result){
if (counters.every(x => x === 0)){
console.log(result);
return;
}
for (var i=0; i<counters.length; i++){
if (counters[i] > 0){
_counters = counters.slice();
_counters[i]--;
f(multiset,_counters,result + multiset[i]);
}
}
}
f(['A','B'],[3,3],'');
This is not full answer, just an idea.
If your strings has fixed number of only two letters I'll go with binary tree and good recursion function.
Each node is object that contains name with prefix of parent name and suffix A or B furthermore it have numbers of A and B letters in the name.
Node constructor gets name of parent and number of A and B from parent so it needs only to add 1 to number of A or B and one letter to name.
It doesn't construct next node if there is more than three A (in case of A node) or B respectively, or their sum is equal to the length of starting string.
Now you can collect leafs of 2 trees (their names) and have all permutations that you need.
Scala or some functional language (with object-like features) would be perfect for implementing this algorithm. Hope this helps or just sparks some ideas.
Since you actually want to generate the permutations instead of just counting them, the best complexity you can hope for is O(size_of_output).
Here's a good solution in java that meets that bound and runs very quickly, while consuming negligible space. It first sorts the letters to find the lexographically smallest permutation, and then generates all permutations in lexographic order.
It's known as the Pandita algorithm: https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
import java.util.Arrays;
import java.util.function.Consumer;
public class UniquePermutations
{
static void generateUniquePermutations(String s, Consumer<String> consumer)
{
char[] array = s.toCharArray();
Arrays.sort(array);
for (;;)
{
consumer.accept(String.valueOf(array));
int changePos=array.length-2;
while (changePos>=0 && array[changePos]>=array[changePos+1])
--changePos;
if (changePos<0)
break; //all done
int swapPos=changePos+1;
while(swapPos+1 < array.length && array[swapPos+1]>array[changePos])
++swapPos;
char t = array[changePos];
array[changePos] = array[swapPos];
array[swapPos] = t;
for (int i=changePos+1, j = array.length-1; i < j; ++i,--j)
{
t = array[i];
array[i] = array[j];
array[j] = t;
}
}
}
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder line = new StringBuilder();
generateUniquePermutations("banana", s->{
if (line.length() > 0)
{
if (line.length() + s.length() >= 75)
{
System.out.println(line.toString());
line.setLength(0);
}
else
line.append(" ");
}
line.append(s);
});
System.out.println(line);
}
}
Here is the output:
aaabnn aaanbn aaannb aabann aabnan aabnna aanabn aananb aanban aanbna
aannab aannba abaann abanan abanna abnaan abnana abnnaa anaabn anaanb
anaban anabna ananab ananba anbaan anbana anbnaa annaab annaba annbaa
baaann baanan baanna banaan banana bannaa bnaaan bnaana bnanaa bnnaaa
naaabn naaanb naaban naabna naanab naanba nabaan nabana nabnaa nanaab
nanaba nanbaa nbaaan nbaana nbanaa nbnaaa nnaaab nnaaba nnabaa nnbaaa

C Table implemented by an array

Basically I'm trying to implement a table with help of an array. The array functionality is already given and should not be altered. What I'm having trouble configuring is my table_remove function. Keep in mind that I'm not striving for the most effective way to do this.
What I tried to do is loop through the entire table to find if there is a key that matches.
If the key is found, save the position.
If not exit.
So after the position is found I set it to free the key & value on that position in hope that it will 'remove' the key & value pair from that position. However, my given test program returns "Removing the last element from a table does not result in an empty table.". If I add in the end "array_setVal(array, NULL, index) then the entire program crashes (Probably because it tries to write on that null position further on in the test).
So now I'm wondering if I'm approaching this issue the wrong way and have to do further operations to actually remove the value from the position without sort of messing up the position itself so next time I use table_insert, the position will be empty and another key & value pair will be inserted in that spot.
int saveRemovedIndex = -1;
/* Check if the key already exists */
for(int indexCounter = 0; indexCounter <= MAXINDEX; indexCounter++){
i = array_inspectValue(t->values, indexCounter);
if (t->cf(i->key,key)==0) {
saveRemovedIndex = indexCounter;
break;
}
}
/* Checks if the key actually exists in the table.
* If it exists, remove it. Else quit.*/
if (saveRemovedIndex != -1) {
i = array_inspectValue(t->values, saveRemovedIndex);
if(t->keyFree!=NULL) {
t->keyFree(i->key);
}
if(t->valueFree!=NULL) {
t->valueFree(i->value);
}
} else {
return;
}

What exactly does the outermost visit strategy do in Rascal?

I wrote the below Rascal code that is supposed to build a tree out of a map from node names to nodes, starting at the node mapped from "top". It should repeatedly replace the children of all nodes that have strings as children in result by the nodes nodeMap maps them to, until nothing changes anymore (fixpoint).
getNode returns the node a map[str,node] maps it to, or the key itself if it is not present as a key in the map. This works fine, as proves the fact that other code at the bottom of this question does work. However, the code directly below seems to run infintely even on very small inputs.
node nodeMapToNode(map[str, node] nodeMap) {
node result = nodeMap["top"];
return outermost visit(result) {
case node n: {
if ([*str children] := getChildren(n)) {
insert makeNode(getName(n), [getNode(child, nodeMap) | child <- children]);
}
}
}
}
The following code does work and returns in an instant on small inputs as I expected. This is, however, exactly what I understood outermost-visiting should do from what I understood from the Rascal tutor.
Can anyone explain to me what the difference between these code snippets is (besides the way they are written) and what I thus misunderstood about the effect of outermost visit? Also, I'd like to know if a shorter and/or nicer way to write this code - using something like outermost-visiting instead of writing the fixpoint by hand - does exist.
node nodeMapToNode(map[str, node] nodeMap) {
node result = nodeMap["top"];
node lastResult;
do {
lastResult = result;
result = visit(lastResult) {
case node n: {
if ([*str children] := getChildren(n)) {
insert makeNode(getName(n),
[getNode(child, nodeMap) | child <- children]);
}
}
}
} while (result != lastResult);
return result;
}
What is outermost?
The rascal tutor is very compact in it's explanation but let's start from there.
repeat a top-down traversal as long as the traversal changes the resulting value (compute a fixed-point).
which in rascal terms means that this:
r = outermost visit(x) {
case str s => s + "."
when size(s) < 3
};
is syntactic sugar for:
r = x;
solve(r) {
r = top-down visit(r) {
case str s => s + "."
when size(s) < 3
};
}
I think there are two common cases were outermost/innermost makes sense:
your replacement should be repeated multiple times on the same node
your replacement generate new nodes that match other patterns
Your specific example
Regarding the example in your question. The other manually rewritten outermost is actually an innermost. The default visit strategy is bottom-up.
In general, an bottom-up visit of the tree is a quicker than a top-down. Especially when you are rewriting it, since Rascal is immutable, building a new tree bottom-up is quicker.
So, perhaps replace your code with an innermost visit instead of an outermost?

Getting list elements from Prolog in a C interface

I try to implement a C interface using a Prolog script based on GNU Prolog. My problem is to get single elements of a nested Prolog list.
Actually my C code looks like
...
int func;
PlTerm arg[10];
PlTerm *sol_gb;
PlBool res;
int nmb;
char *strHead;
char *strTail;
PlLong nummero;
PlTerm pl_nummero;
Pl_Start_Prolog(argc, argv);
Pl_Query_Begin(PL_TRUE);
arg[0] = Pl_Mk_String(strRName);
arg[1] = Pl_Mk_Variable();
arg[2] = Pl_Mk_Variable();
arg[3] = Pl_Mk_String("true");
res = Pl_Query_Call(func, 4, arg);
sol_gb = Pl_Rd_List(arg[2]);
nmb = Pl_List_Length(sol_gb[0]);
strHead = Pl_Write_To_String(sol_gb[0]);
printf("strHead = %s\n",strHead);
strTail = Pl_Write_To_String(sol_gb[1]);
printf("strTail = %s\n",strTail);
...
The Prolog list returned in arg[2] looks like
[ [ Spezial Bolognese,
[2, ,Zwiebeln,300,gramm,Hackfleisch,10, ,Tomaten,
100,ml,Sahne,500,gramm,Spaghetti]
],
[ Spaghetti Bolognese,
[2, ,Zwiebeln gehackt,300,gramm,Hackfleisch,10, ,Fleischtomaten,
100,ml,Sahne,500,gramm,Spaghetti]
]
]
The output of the conversion into a String is
strHead = [Spezial Bolognese,[2, ,Zwiebeln gehackt,300,gramm,Hackfleisch,
10, ,Fleischtomaten,100,ml,Sahne,500,gramm,Spaghetti]]
strTail = [[Spaghetti Bolognese,[2, ,Zwiebeln gehackt,300,gramm,Hackfleisch,
10, ,Fleischtomaten,100,ml,Sahne,500,gramm,Spaghetti]]]
So I assume, I am "nearly there" but as I have to re-activate my C knowledge I do not get the solution how to enter in the next level of the list to get finally each element as string ("Spezial Bolognese", next step: "2", "Zwiebeln" etc.).
How can I step through the Prolog list in C?
I would be very happy about every hint, thank you again!
To get the content of a list from the C-code you can use 2 kind of functions.
First possibility (simple since the list is seen as a flat object but requires more memory and needs a proper list, i.e. does not work for lists not terminated by [])
int Pl_Rd_Proper_List_Check(PlTerm the_prolog_list, PlTerm *the_array_receiving_arguments);
this functions receives an array (it is up to you to ensure it is large enough), stores each element of the list in the array and returns the total number of elements. Example:
PlTerm list = ...some Prolog list...
int nElem = Pl_List_Length(list);
PlTerm *elem = (PlTerm *) calloc(nElem, sizeof(PlTerm));
Pl_Rd_Proper_List_Check(list, elem);
int i;
for(i = 0; i < nElem; i++) {
// here there is an argument in elem[i], let's print it
Pl_Write(elem[i]);
}
Second possibility (more general but see a list as a chained list, each cell contains the head and a tail (a list))
PlTerm *Pl_Rd_List(PlTerm the_prolog_list);
This function returns an array of 2 elements corresponding to the head and the tail of the received list. This function should be called on each element of the list; either you know the number of elements or you test the end of the list (e.g. waiting for the end of list atom []). Here is a code doing this (it is expected to be inside the above loop since we know the second argument of the list is a nested list.
PlTerm list = ... some Prolog list...;
while(!Pl_Un_Atom(Pl_Atom_Nil(), list)) {
PlTerm *lst_arg = Pl_Rd_List(list); // [0] = head element, [1] = tail list
// here there is an argument in lst_arg[0], let's print it
Pl_Write(lst_arg[0]);
list = lst_arg[1];
}
In your example, the first list looks like:
[ 'Spezial Bolognese',
[2,' ','Zwiebeln',
300,'gramm','Hackfleisch',
10,' ','Tomaten',
100,'ml','Sahne',
500,'gramm','Spaghetti']
]
so the second element is a nested list. The following code uses the first method for the above list (which has 2 elements), and the second method for the nested list:
nElem = Pl_List_Length(sol_gb[0]);
PlTerm *elem = (PlTerm *) calloc(nElem, sizeof(PlTerm));
Pl_Rd_Proper_List_Check(sol_gb[0], elem);
int i;
for(i = 0; i < nmb; i++) {
if (i != 1) {
Pl_Write(elem[i]);
printf("\n");
} else { // we know it is a list
printf("(");
PlTerm list = elem[i];
while(!Pl_Un_Atom(Pl_Atom_Nil(), list)) {
PlTerm *lst_arg = Pl_Rd_List(list); // [0] = head element, [1] = tail list
printf(" ");
Pl_Write(lst_arg[0]);
list = lst_arg[1];
}
printf(" )\n");
}
}
Here should be the output
Spezial Bolognese
( 2 Zwiebeln 300 gramm Hackfleisch 10 Tomaten 100 ml Sahne 500 gramm Spaghetti )
The sample code you give of the lists of lists sounds like a textbook example of a very bad choice for knowledge representation. I strongly suggest you change it to a more declarative representation. Something like:
% pizza(Name, Steps)
pizza('Spezial Bolognese', ...).
...
where Steps could be a list of step(...) terms. This would potentially make processing the information easier and more efficient. For example, in the Prolog side, you could then use the standard arg/3 predicate to access a specific element in a step. With lists, you have no choice other than traversing them every time you want an element other than the list head.

Delete records using integer list

I want to Loop through the array of integers and want to remove the items in the TLToProcess list which i have stored in the array of integers
here is the code
I want to remove only the selected in the list integer
iSize.add(TLToProcess.size());
if(TLToProcess[i].Scan_In1__c==null)
{
if(TLToProcess[i].typew__c=='Pending')
{
TLForMissingHHhh.add(TLToProcess[i]);
}
}
else if ( c[i].Scan_In1__c!=null)
{
if (TLToProcess[i].typew__c=='Pending' )
{
TLToProcess[i].typew__c='Processed';
}
}
}
Now i want to remove record 1 by 1 from TLToProcess using
remove() can any body tell me how to do it.
Thanks
Anu
Not sure I understand your problem, but if what you're trying to avoid is modifying your List of integers inside a loop and getting this error: {"Collection was modified; enumeration operation may not execute."} you can create a copy of your List(.ToList()) and use it to iterate, and this way you can call Remove() safely.
List<Int32> arr = new List<Int32>();
for (int i = 0; i < 10; i++)
{
arr.Add(i);
}
foreach(var o in arr.ToList())
{
arr.Remove(o);
}
Is that the intent?

Resources