ANTLR3 inject an int into my tree - antlr3

Is it possible to do what I'm attempting here? Or, perhaps I'm approaching it wrong?
arrayDef
: { int c = 0; }
('['']' {c++;})+
-> ARRAY /* somehow inject c here */
;

Why not use the ChildCount of your ARRAY tree node?
arrayDef
: ('[' ']')+
-> ^(ARRAY '['+)
;

Related

range-based for loop over references

This is question is out of curiosity, not necessity. One way I have found C++11's range based for loop useful is for iterating over discrete objects:
#include <iostream>
#include <functional>
int main()
{
int a = 1;
int b = 2;
int c = 3;
// handy:
for (const int& n : {a, b, c}) {
std::cout << n << '\n';
}
I would like to be able to use the same loop style to modify non-const references too, but I believe it is not allowed by the standard (see Why are arrays of references illegal?):
// would be handy but not allowed:
// for (int& n : {a, b, c}) {
// n = 0;
// }
I thought of two workarounds but these seem like they could incur some minor additional cost and they just don't look as clean:
// meh:
for (int* n : {&a, &b, &c}) {
*n = 0;
}
// meh:
using intRef = std::reference_wrapper<int>;
for (int& n : {intRef (a), intRef (b), intRef (c)}) {
n = 0;
}
}
So the question is, is there a cleaner or better way? There may be no answer to this but I'm always impressed with the clever ideas people have on stackoverflow so I thought I would ask.
Picking up #Sombrero Chicken's idea, here is an approach with less typing:
template <class ...Args> constexpr auto ref(Args&&... args)
{
using First = std::tuple_element_t<0, std::tuple<Args...>>;
using WrappedFirst = std::reference_wrapper<std::remove_reference_t<First>>;
constexpr auto n = sizeof...(Args);
return std::array<WrappedFirst, n>{std::ref(args)...};
}
which can be used via
for (int& n : ref(a, b, c))
n = 0;
Instead of constructing a reference_wrapper yourself you could use std::ref, that's as far as you can get:
using std::ref;
for (int& n : {ref(a), ref(b), ref(c)}) {
n = 0;
}

Double Linked List Insertion in Between

I am trying to write the code for the following question:
Insert an element(sum of neighbors) between every pair of consecutive elements?
Example: if input is
12 23 34 45 for n=4
Output should be:
12 35 23 57 34 79 45
The code I wrote is:
struct node *InsBet(node *head) {
node *i,*j,*t;
i=head;
while(i->next!=NULL) {
t = (node*)malloc(sizeof(node));
t->data = i->data + i->next->data;
i->next = t;t->prev = i;
t->next = i->next;i->next->prev = t;
i = i->next;
}
return head;
}
Upon printing the array it is crashing my terminal.
My print program is:
void PrintList(node *head) {
node *i;
i=head;
while(i!=NULL) {
printf("%d ",i->data);
i=i->next;
}
}
The first problem is that you're overriding i->next before copying it to t->next
Switch the order of
i->next = t;t->prev = i;
t->next = i->next;i->next->prev = t;
into
t->next = i->next; i->next->prev = t;
i->next = t; t->prev = i;
To elaborate, assume you have a chain of 2 elements in your list: A-->B, and you want to add the temporary element between, so you create t, but since the first thing you do is overwrite the forward pointer of the first element (A in this case), you lose any chance of ever accessing B again. Instead, you assign into the forward pointer of the temporary element the address of itselfm creating an infinite loop.
The second problem is that you advance the current pointer (i) by only one link, which means it would now point to the temporary element you've just added, and you would try to add an additional temporary element between t and B. This would cause an infinite loop - instead advance i by -
i = t->next;
The above answer explained it very well but just to give you a working code, here you go:
PS, you don't need to return the head pointer because its passed by reference and there is no use in returning it
void InsBet(node *head) {
node *i,*t;
i=head;
while(i->next!=NULL) {
t = (node*)malloc(sizeof(node));
t->data = i->data + i->next->data;
t->prev = i;
t->next = i->next;
i->next = i->next->next;
i->prev = t;
i = t->next;
}
}

How do I find the depth/level of a node in a non-binary tree?

I have a tree structure where each node can have essentially unlimited children, it's modelling the comments for a blog.
I'm trying to figure out, given the ID of a specific comment, at what depth/level that comment lies in the tree.
I was following this guide that explains it for binary trees, but when adapting it into non-binary trees I'm having some trouble.
Here's my attempt so far (in Swift):
func commentLevelRecursive(comment: Comment, commentID: String, currentLevel: Int) -> Int {
if comment.identifier == commentID {
return currentLevel
}
var newLevel = currentLevel
for reply in comment.replies {
newLevel = commentLevelRecursive(reply, commentID: commentID, currentLevel: currentLevel + 1)
}
return newLevel
}
But it always seemingly returns 1. I think this is because newLevel always gets increased from 0 to 1 then returns.
Could anyone give me some insight into where I'm going wrong?
Binary tree is a special case where each node has only two children.
The method used to find node level can be extended to a common tree.
The idea is the same:
level(P) = max(level(C) for each child node C of P)+1
int MaxDepth(int x,int parent){
int mx = 0;
for(int i = 0;i < graph[x].size();i++)
if(graph[x][i]!=parent){
mx = max(MaxDepth(graph[x][i],x),mx);
}
return mx + 1;
}

How can you iterate a k-ary tree?

Assume you have a generic k-ary tree like this one or this one
Repeating the latter here:
template <typename T>
struct TreeNode
{
T* DATA ; // data of type T to be stored at this TreeNode
vector< TreeNode<T>* > children ;
void insert( T* newData ) ;
// runs f on this and all children of this
void preorder( function<void (T*)> f )
{
f( this->DATA ) ; // exec f on this
for( int i = 0 ; i < children.size(); i++ )
children[i]->preorder( f ) ; // exec f on each child
}
} ;
template <typename T>
struct Tree
{
TreeNode<T>* root;
// TREE LEVEL functions
void clear() { delete root ; root=0; }
void insert( T* data ) { if(root)root->insert(data); }
} ;
Now normally, you have pre-order and post-order traversals as recursive member functions of TreeNode as shown above. But say you don't want to be passing functions around, you want to visit each node in the tree from outside the class (ie just given a Tree object).
How can you do it?
I would approach this by defining a PreorderIterator class that maintained state about where it was in the traversal. It would have methods for returning the current node and for advancing one step in the traversal.
You would have to be careful if the tree structure could mutate during the life of the iterator. Perhaps the tree could maintain a modification count; the iterator could capture the count at the start and check for changes at each access (and throwing an exception if it found one).
One easy approach is to load the tree into a list and then walk the list when you need. The list would only be a list of pointers and therefore not that expensive. To do that you would use a modified version of the trie traversal algorithm:
void traverse(Node n){
if(null == n) return;
for( Node c: n.children){
visit( c );
traverse( c );
}
}
You would use the visit to actually load your list. So something like
List<Node> getListToIterate(Node n){
List<Node> result = new ArrayList<Node>();
traverse(n,resutl);
return result;
}
void traverse(Node n, List list){
if(null == n) return;
for( Node c: n.children){
list.add( c );
traverse( c );
}
}
Also, if you decide, you can wrap this algorithm in a TreeIterator class that would track where you are in the list.

Preorder to postorder in tree

I have a question i want to create postorder from inorder and preorder, but i don't wana use reconstruction of tree, i want only recursive do this. I code this, and at this moment, i have a part of, right side of tree in preorder( First char in preorder is root, i find this in inorder, and i have left and right side, i recurency translate to right side), but i have a problem with left side of tree. I don't have no idea to do this. Can someone give me some of suggestion or code ? Please help :)
public static String a(String pre, String in, int start, int end) {
char c = pre.charAt(start); //first char in preorder is root
int ix = find(pre, in, c); // if we find this char in inorder translation we know where is left and right side of tree
stack += c;
if (start == 0 && flaga == true) {
left = pre.substring(1, ix + 1);
right = pre.substring(ix + 1, end);
flaga = false;
return a(right, in, 0, end);
}
String reverse = new StringBuffer(stos).reverse().toString();
//stack to see
// System.out.println("STACK " + stos);
if (start < right.length()-1) {
return a(right, in, start + 1, end - 1);
}
return "";
}
public static int find(String a, String b, char c) {
int b_l = b.length();
for (int i = 0; i < b_l; ++i)
if (b.charAt(i) == c)
return i;
return -1;
First Test :
String pre = "FBADCEGIH";
String inorder = "ABCDEFGHI";
ANswer should be : //A, C, E, D, B, H, I, G, F
My problem is with left side of tree, i don't have any idea to do this correct, and i'm not sure my code work for all situation of preorder and inorder.

Resources