Treeview node reselection - c#-2.0

I'm working on compact framework 2.0 and using c#.
I have problem with treeview node reselection. Scenario is like this :
temp0
temp1
temp2
temp3
I have some node in treeview and using up and down arrow for moving node up and down.
but problem is that once i select a node and clicking up arrow, node is moved up
and I cann't select node just below this node.
Suppose I select temp3 and press up arrow, this temp3 is replaced by temp2.
like this:
temp0
temp1
temp3
temp2
after this I cann't select temp2 but able to select temp3 and other node whatever is up.
I'm using this code for up arrow:
int paramPos = this.treeView1.SelectedNode.Index;
if (paramPos > 0)
{
System.Windows.Forms.TreeNode tempNode = this.treeView1.SelectedNode;
this.treeView1.Nodes[paramPos] = this.treeView1.Nodes[paramPos - 1];
this.treeView1.Nodes[paramPos - 1] = tempNode;
this.treeView1.SelectedNode = this.treeView1.Nodes[paramPos - 1];
foreach (System.Windows.Forms.TreeNode tnode in this.treeView1.Nodes)
{
ArgumentNumberInfo ai = (ArgumentNumberInfo)tnode.Tag;
ai.ArgNo = tnode.Index + 1;
}
treeView1.SelectedNode = tempNode;
this.treeView1_AfterSelect(null, null);
}
}
After pressing up arrow node is going to up but i cann't able to select node below this.
Node0
node1
node2
node3
If you select node3 and click on up arrow node3 will go up and node2 will come down but you cann't select node2.
please give me some clue why is it happening.
Thnx for your time.

Treeview nodes are maintained by an internal linked list. I think the method that you're using to swap them around is confusing that linked list. Here's the part of the code that I'm referring to:
System.Windows.Forms.TreeNode tempNode = this.treeView1.SelectedNode;
this.treeView1.Nodes[paramPos] = this.treeView1.Nodes[paramPos - 1];
this.treeView1.Nodes[paramPos - 1] = tempNode;
Try the following in place of the code above:
System.Windows.Forms.TreeNode tempNode = this.treeView1.SelectedNode;
this.treeView1.Remove(tempNode);
this.treeView1.Insert(paramPos - 1, tempNode);

Related

Merge two sorted linked lists: space complexity

I am looking at the following Geeks for Geeks problem:
Given two sorted linked lists consisting of N and M nodes respectively. The task is to merge both of the list (in-place) and return head of the merged list.
Example 1
Input:
N = 4, M = 3
valueN[] = {5,10,15,40}
valueM[] = {2,3,20}
Output: 2 3 5 10 15 20 40
Explanation: After merging the two linked
lists, we have merged list as 2, 3, 5,
10, 15, 20, 40.
Below answer is the GFG answer. I don't understand how its space complexity is O(1). We are creating a new node, so it must be O(m+n).
Node* sortedMerge(Node* head1, Node* head2)
{
struct Node *dummy = new Node(0);
struct Node *tail = dummy;
while (1) {
if (head1 == NULL) {
tail->next = head2;
break;
}
else if (head2 == NULL) {
tail->next = head1;
break;
}
if (head1->data <= head2->data){
tail->next = head1;
head1 = head1->next;
}
else{
tail->next = head2;
head2 = head2->next;
}
tail = tail->next;
}
return dummy->next;
}
Could someone explain how the space complexity is O(1) here?
I can't understand how it's space complexity is O(1). Since we are creating a new node so it must be O(m+n).
Why should it be O(m+n) when it creates one node? The size of that node is a constant, so one node represents O(1) space complexity. Creating one node has nothing to do with the size of either of the input lists. Note that the node is created outside of the loop.
It is actually done this way to keep the code simple, but the merge could be done even without that dummy node.

Reverse of a Linked List using iteration

Given a pointer to a linked list, I'm trying to reverse a linked using iteration(not recursive approach) in java. This is my code snippet.
Node reverse(Node head)
{
Node cur = head.next;
Node prev = head;
Node nxt;
while(cur!=null){
nxt = cur.next;
cur.next = prev;
prev = cur;
cur = nxt;
}
return prev;
}
But when I run it it gives error-"Time Limit Exceeded". So, there might be an infinite loop somewhere but I can't figure out where. Any help will be appreciated. Thank you.
You have not set next pointer of head node to null. firstnode.next is still pointing to the second node of given linkedlist which resulted in infinite looping.
Node cur = head.next;
Node prev = head;
prev.next = null; // add this

Coding a type of random walk in Neo4j using the Traversal Framework

I'm currently working on a graph where nodes are connected via probabilistic edges. The weight on each edge defines the probability of existence of the edge.
Here is an example graph to get you started
(A)-[0.5]->(B)
(A)-[0.5]->(C)
(B)-[0.5]->(C)
(B)-[0.3]->(D)
(C)-[1.0]->(E)
(C)-[0.3]->(D)
(E)-[0.3]->(D)
I would like to use the Neo4j Traversal Framework to traverse this graph starting from (A) and return the number of nodes that have been reached based on the probability of the edges found along the way.
Important:
Each node that is reached can only be counted once. -> If (A) reaches (B) and (C), then (C) need not reach (B). On the other hand if (A) fails to reach (B) but reaches (C) then (C) will attempt to reach (B).
The same goes if (B) reaches (C), (C) will not try and reach (B) again.
This is a discrete time step function, a node will only attempt to reach a neighboring node once.
To test the existence of an edge (whether we traverse it) we can generate a random number and verify if it's smaller than the edge weight.
I have already coded part of the traversal description as follows. (Here it is possible to start from multiple nodes but that is not necessary to solve the problem.)
TraversalDescription traversal = db.traversalDescription()
.breadthFirst()
.relationships( Rels.INFLUENCES, Direction.OUTGOING )
.uniqueness( Uniqueness.NODE_PATH )
.uniqueness( Uniqueness.RELATIONSHIP_GLOBAL )
.evaluator(new Evaluator() {
#Override
public Evaluation evaluate(Path path) {
// Get current
Node curNode = path.endNode();
// If current node is the start node, it doesn't have previous relationship,
// Just add it to result and keep traversing
if (startNodes.contains(curNode)) {
return Evaluation.INCLUDE_AND_CONTINUE;
}
// Otherwise...
else {
// Get current relationhsip
Relationship curRel = path.lastRelationship();
// Instantiate random number generator
Random rnd = new Random();
// Get a random number (between 0 and 1)
double rndNum = rnd.nextDouble();
// relationship wc is greater than the random number
if (rndNum < (double)curRel.getProperty("wc")) {
String info = "";
if (curRel != null) {
Node prevNode = curRel.getOtherNode(curNode);
info += "(" + prevNode.getProperty("name") + ")-[" + curRel.getProperty("wc") + "]->";
}
info += "(" + curNode.getProperty("name") + ")";
info += " :" + rndNum;
System.out.println(info);
// Keep node and keep traversing
return Evaluation.INCLUDE_AND_CONTINUE;
} else {
// Don't save node in result and stop traversing
return Evaluation.EXCLUDE_AND_PRUNE;
}
}
}
});
I keep track of the number of nodes reached like so:
long score = 0;
for (Node currentNode : traversal.traverse( nodeList ).nodes())
{
System.out.print(" <" + currentNode.getProperty("name") + "> ");
score += 1;
}
The problem with this code is that although NODE_PATH is defined there may be cycles which I don't want.
Therefore, I would like to know:
Is there is a solution to avoid cycles and count exactly the number of nodes reached?
And ideally, is it possible (or better) to do the same thing using PathExpander, and if yes how can I go about coding that?
Thanks
This certainly isn't the best answer.
Instead of iterating on nodes() I iterate on the paths, and add the endNode() to a set and then simply get the size of the set as the number of unique nodes.
HashSet<String> nodes = new HashSet<>();
for (Path path : traversal.traverse(nodeList))
{
Node currNode = path.endNode();
String val = String.valueOf(currNode.getProperty("name"));
nodes.add(val);
System.out.println(path);
System.out.println("");
}
score = nodes.size();
Hopefully someone can suggest a more optimal solution.
I'm still surprised though that NODE_PATH didn't not prevent cycles from forming.

Some difficulties of designing with types in F# by simple graph example

There is oriented graph:
We are adding node and edge to it:
and then removing some other (by the algorithm, it doesn't matter here):
I had tried to do this in F#, but I cannot choose properly architecture decisions because of my little experience.
open System.Collections.Generic
type Node = Node of int
type OGraph(nodes : Set<Node>,
edges : Dictionary<Node * int, Node>) =
member this.Nodes = nodes
member this.Edges = edges
let nodes = set [Node 1; Node 2; Node 3]
let edges = Dictionary<Node * int, Node>()
Array.iter edges.Add [|
(Node 1, 10), Node 2;
(Node 2, 20), Node 3;
|]
let myGraph = OGraph(nodes, edges)
myGraph.Nodes.Add (Node 4)
myGraph.Edges.Add ((Node 2, 50), Node 4)
myGraph.Edges.Remove (Node 2, 20)
myGraph.Nodes.Remove (Node 3)
How to add empty node? I mean, it may be 3 or 4 or even 100500. If we add node without number, then how we can use it to create edge? myGraph.Edges.Add ((Node 2, 50), ???) In imperative paradigm it would be simple because of using named references and Nulls, we can just create Node newNode = new Node() and then use this reference newNode, but seems that in F# this is a bad practice.
Should I specify separate types Node and Edge or use simple types instead? Or may be some other representation, more complicated?
It is better to use common .NET mutable collections (HashSet, Dictionary etc.), or special F# collections (Set, Map, etc.)? If collections are large, it is acceptable in terms of performance to copy entire collection every time it should be changed?
The graph itself is easy enough to model. You could define it like this:
type Graph = { Node : int option; Children : (int * Graph) list }
If you will, you can embellish it more, using either type aliases or custom types instead of primitive int values, but this is the basic idea.
You can model the three graphs pictured in the OP like the following. The formatting I've used looks quite verbose, but I deliberately formatted the values this way in order to make the structure clearer; you could write the values in a more compact form, if you'd like.
let x1 =
{
Node = Some 1;
Children =
[
(
10,
{
Node = Some 2;
Children =
[
(
20,
{
Node = Some 3;
Children = []
}
)
]
}
)
]
}
let x2 =
{
Node = Some 1;
Children =
[
(
10,
{
Node = Some 2;
Children =
[
(
20,
{
Node = Some 3;
Children = []
}
);
(
50,
{
Node = None;
Children = []
}
)
]
}
)
]
}
let x3 =
{
Node = Some 1;
Children =
[
(
10,
{
Node = Some 2;
Children =
[
(
50,
{
Node = Some 3;
Children = []
}
)
]
}
)
]
}
Notice the use of int option to capture whether or not a node has a value.
The Graph type is an F# record type, and uses the F# workhorse list for the children. This would be my default choice, and only if performance becomes a problem would I consider other data types. Lists are easy to work with.
Sine if these are easy:
Use Option - then an empty node is None
Maybe - depends on problem
This depends on your specific problem you are solving - the F# collections tend to be immutable and some operations are fast, but the .NET collections have other operations which are fast.

Propel NestedSet creating Balanced Tree

I'm trying to use Propel's NestedSet feature. However, I'm missing something about inserting such that the tree is balanced as it is created (i.e. fill it in horizontally).
Say I have these elements:
root
r1c1 r1c2
r2c1 r2c2
I want to insert r2c3 as the 1st child of r1c2 (i.e. fill row 2 before starting on row 3).
My first stab at this was to create this function:
function where(User $root,$depth=0)
{
$num = $root->getNumberOfDescendants();
if ( $num < 2 )
return $root;
foreach($root->getChildren() as $d)
{
if ( $d->getNumberOfChildren() < 2 )
{
return $d;
}
}
foreach($root->getChildren() as $d)
{
return where($d, $depth+1);
}
}
However, this will insert a child on r2c1, rather at r1c2 as I want.
Is there a way to insert an entry into the tree at the next available spot somehow?
TIA
Mike
OK, thanks to http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/, I found that this algorithm will do what I want:
function where($root)
{
$num = $root->getNumberOfDescendants();
if ( $num < 2 )
return $root;
$finder = DbFinder::from('User')->
where('LeftId','>=',$root->getLeftId())->
where('RightId','<=',$root->getRightId())->
whereCustom('user.RightId = user.LeftId + ?',1,'left')->
whereCustom('user.RightId = user.LeftId + ?',3,'right')->
combine(array('left','right'),'or')->
orderBy('ParentId');
return $finder->findOne();
}
It basically executes this SQL:
SELECT u.*
FROM user u
WHERE u.LEFT_ID >= $left AND u.RIGHT_ID <= $right AND
(u.RIGHT_ID = u.LEFT_ID+1 OR u.RIGHT_ID = u.LEFT_ID+3)
ORDER BY u.PARENT_ID
LIMIT 1
A leaf has RIGHT=LEFT+1, A node with 1 child has RIGHT=LEFT+3. By adding the ORDER BY u.PARENT_ID, we find the highest node in the tree available. If you use LEFT_ID or RIGHT_ID, it does not balance the tree.

Resources