I was assigned a problem to solve using various search techniques. The problem is very similar to the Escape From Zurg problem or the Bridge and Torch problem. My issue is that I am lost as to how to represent the data as a tree.
This is my guess as to how to do it, but it doesn't make much sense for searching.
Another way could be to use a binary tree sorted by their walking time. However, I'm still not sure if I'm attacking this problem correctly since search algorithms don't necessarily require binary trees.
Any tips on representing this data would be appreciated.
Generally when you are using a tree search to solve a problem, each node represents some possible "state" of the world (who's on what side of the bridge, for example), and the children of each node represent all possible "successor states" (new states that can be reached in one move from the previous state). A depth-first search then represents trying one option until it dead-ends, then backing up to the last state where another option was available and trying it out. A breadth-first search represents trying out lots of options in parallel and seeing when the first of them find the goal node.
In terms of the actual way of encoding this, you would represent this as a multiway tree. Each node would probably contain the current state, plus a list of pointers to child nodes.
Hope this helps!
U could use something like this:
public class Node
{
public int root;
public List<Node> neighbours;
public Node(int x)
{
root=x;
}
public void setNeighboursList(List<Node> l)
{
neighbours = l;
}
public void addNeighbour(Node n)
{
if(neighbours==null) neighbours = new ArrayList<Node>();
neighbours.add(n);
}
...
}
public class Tree
{
public Node root;
....
}
Related
I'm still new to coding and I'm trying to learn how to create a linked list. What does this part mean? I can't seem to visualize this in my head.
static class Node {
int data;
Node next;
Node(int d){
data = d;
next = null;}
}
So this is a simple visual of a linked list. Your code represents a node class, so thats just the framework for a node. But you can think of that code representing one node, so it could represent the fourth node in this diagram. Thus, its data value would be {D} and its next value would be null.
In a linked list, the next node object it represented by the next variable. So if the node you are looking at is the second node, then your next variable will be the third node.
I've encountered the following interview questions online. Based on my understanding, it's asked you to design a data structure to simulate the file system. Can anyone give me some hints?
// addMapping("/foo/bar/x", "XController")
// addMapping("/foo/bar/z", "ZController")
// addMapping("/foo/baz", "BazController");
//getMapping("/foo/bar/x") -> ["XController"]
//getMapping("/foo/bar") -> ["XController", "ZController"]
public void addMapping(String path, String destination) {
//candidate TODO
}
public List<String> getMapping(String path) {
//candidate TODO
}
I think the best structure to use for this mapping is a Trie or even better its compressed version - a Patricia Tree(a.k.a radix tree). The idea is the following - both structures store prefixes of dictionary words. When a user queries for a given path you traverse the structure(be it a trie or a radix tree) according to the query string. After that you do any walk over the subtree under the node where you end up and print all the controllers associated with the nodes there.
I want to design a map like in traveling salesman problem.
There are a number of nodes, some connected to another.
One node can be connected to many other nodes.
I have designed some, which one is better ? Or maybe there are another better design ?
1.)
class Node {
private int ID;
private int position-x;
private int position-y;
}
class Connection {
private int ID;
private Node first;
private Node second;
public void ConnectTwoNodes( Node a, Node b ) { ... }
}
2.)
class Node {
private int ID;
private int position-x;
private int position-y;
private ArrayList<Node> anotherNodes; // array of connected nodes
public void ConnectTo( Node another ) { ... }
}
Your language seems to be C++.
Your solution 1. has the following problems:
class Connection seems to "aggregate" the Nodes. It should rather be an association in OOspeak (a pointer to a Node to make it understandable to mere mortals)
a Connection object has absolutely no reason to exist, unless it connects 2 Nodes. So the function of ConnectTwoNodes belongs in a constructor. In other words rename it to Connection.
In your second solution it also seems that a Node contains the other Nodes. But in reality they exist independently. Again, you need associations, or pointers to other Nodes.
I actually prefer the 1. approach. Or a non-OO solution with a matrix, with "from" Nodes on one axle and "to" Nodes on the other. It also allows you to handle cases when it's possible to get from New York to Paris, Texas but not vice versa, because there are no more flights in the afternoon. In other words a directional graph.
I have a RadTreeView C# component. The tree is nested, so some Nodes have their sub-trees, stored in Nodes property of upper-level Nodes.
Now I need to find a node by value. Node is hidden somewhere in subtrees. If I use call
RadTreeNode rtn= PagesTreeView.Nodes.FindNodeByValue(i.ToString());
where PagesTreeView is my tree, then it searches only across top-level nodes.
How I can Find Node by Value using not only Nodes from the current level of tree, but also dive into subtrees? Do I need to write such recursive search myself or there is a straightforward solution?
Recursively searching the RadComboBox
There isn't a built in function to recursively search, however you can roll your own pretty easiliy. This should work for you (not tested):
RadTreeNode FindNodeRecursive(RadTreeNodeCollection nodes, string value)
{
foreach (RadTreeNode node in nodes)
{
if(node.Value == value)
return node;
if (node.Nodes.Count > 0)
{
FindNodeRecursive(node.Nodes, value);
}
return null;
}
}
And then call it like this:
var node = FindNodeRecursive(PagesTreeView.Nodes, i.ToString());
Yes, you would need to write your own recursive function to do the search. Another option if you are using the ASP.NET AJAX version of the control is the GetAllNodes() method. It returns all nodes in the tree hierarchy (I'm guessing it uses recursion under the hood). Once you have the entire list you would search it for the node you care about. The big drawback with that approach is if you have a lot of nodes the search could be slow and consume a lot of memory. Doing your own recursive search is the best approach.
See this article for more info.
Old question but I faced this same problem in my application, how to search through the hierarchical tree nodes.
I would like to share one correction to previous solutions proposal. When calling FindNodeRecursive() recursively the return value of your recursive call is never being evaluated or assigned to a variable. So, you will always end up with going through the foreach loop and return value is null.
Corrected and tested function code (WPF C#):
RadTreeNode FindNodeRecursive(RadTreeNodeCollection nodes, string value)
{
RadTreeNode ret = null;
foreach (RadTreeNode node in nodes)
{
if(node.Value == value)
return node;
if (node.Nodes.Count > 0)
{
ret = FindNodeRecursive(node.Nodes, value);
}
return ret;
}
}
Function use:
var node = FindNodeRecursive(PagesTreeView.Nodes, i.ToString());
if (node != null) // found
{
;
}
I'm working with WPF and I'm developing a complex usercontrol, which is composed of a tree with rich functionality etc.
For this purpose I used a View-Model design pattern, because some operations couldn't be achieved directly in WPF. So I take the IHierarchyItem (which is a node and pass it to this constructor to create a tree structure)
private IHierarchyItemViewModel(IHierarchyItem hierarchyItem, IHierarchyItemViewModel parent)
{
this.hierarchyItem = hierarchyItem;
this.parent = parent;
List<IHierarchyItemViewModel> l = new List<IHierarchyItemViewModel>();
foreach (IHierarchyItem item in hierarchyItem.Children)
{
l.Add(new IHierarchyItemViewModel(item, this));
}
children = new ReadOnlyCollection<IHierarchyItemViewModel>(l);
}
The problem is that this constructor takes about 3 seconds !! for 200 items on my dual-core.
Am I doing anythig wrong or recursive constructor call is that slow?
Thank you very much!
OK I found a non recursive version by myself, although it uses the Stack.
It traverses the whole tree:
Stack<MyItem> stack = new Stack<MyItem>();
stack.Push(root);
while (stack.Count > 0)
{
MyItem taken = stack.Pop();
foreach (MyItem child in taken.Children)
stack.Push(MyItem);
}
There should be nothing wrong with a recursive implementation of a tree, especially for such a small number of items. A recursive implementation is sometimes less space efficient, and slightly less time efficient, but the code clarity often makes up for it.
It would be useful for you to perform some simple profiling on your constructor. Using one of the suggestions from: http://en.csharp-online.net/Measure_execution_time you could indicate for yourself how long each piece is taking.
There is a possibility that one piece in particular is taking a long time. In any case, that might help you narrow down where you are really spending the time.