## trees – Query sum of values between lo and hi for a stream of numbers

Suppose you have a stream of incoming numbers that you’re storing and at any given instant in time, you want to query the sum of values between a given `lo` and `hi` in the stream you’ve read thus far.

It it possible to solve this problem with segment trees?

The only solution I could come up with is either O(n) insertion and O(log n) query (using a sorted array and prefix sum) or O(log n) insertion and O(n) query (using a binary search tree).

## dnd 5e – Lightning Bolt and trees in DnD 5e

### The rules list a tree trunk as an example of 3/4 cover.

The rules for Three-Quarters Cover state:

A target with three-quarters cover has a +5 bonus to AC and Dexterity saving throws. A target has three-quarters cover if about three-quarters of it is covered by an obstacle. The obstacle might be a portcullis, an arrow slit, or a thick tree trunk.

So an character trying to hide behind a tree trunk that happened to be in the area of effect of lightning bolt would get +5 to their dexterity save. Now, as the DM, it’s really up to you how much cover the tree actually provides. I once had a player insist that all trees granted 3/4 cover, but unfortunately for him, these were really skinny trees, so I generously gave him half cover. It’s up to you to determine the character’s size in relation to the size of your trees, but I recommend sticking with 3/4 as the book suggests, unless you’ve explained to the players that these are really skinny or really thick trees.

### Also the tree is now on fire.

The lightning ignites flammable objects in the area that aren’t being worn or carried.

Setting the players’ cover on fire is a great way to get the players to do something. I don’t actually have any experience doing anything to the players with flaming cover, so I can’t tell you what to do if they decide to hang around near the flaming tree. This is because my players always freak out when their cover is set ablaze. Whenever I feel like a battle isn’t interesting enough because there is too much hiding going on, I set stuff on fire.

Consider the battle in the banquet hall. The ranger and barbarian flipped a wooden long table and were using it for cover. I’m thinking to myself, “I don’t want to walk the bad guys over there to get the ranger because the barbarian is chilling with him.” Then I remembered my favorite combat seasoning: fire. “The captain of the guard lights an arrow on a nearby sconce and shoots it directly into the table.” They think nothing of it, next round I announce, “Some spilled olive oil has caught fire.” They think nothing of it. The battle goes on for another round, and I am finally pleased to announce, “The front side of your table has erupted into a raging inferno. This is the part where rational decision making is no longer an option. For no reason at all (except possibly a highly sensationalized fire), the ranger leaps over the table to engage the guards in melee combat.

The point is, when you use lightning bolt you have an opportunity to increase the stakes of the fight a little bit by setting their cover on fire, which I have often seen lead to some pretty epic and funny moments in battle.

I’m writing a breadth first search algorithm in Haskell that supports pruning. It is guaranteed that the search will never encounter nodes that have been visited before, so I implemented the search as a `filter` along a stream of candidates.

I’m concerned about the efficiency of the code. Is there some slow, bad-practice code that I can try to avoid? What are some possible ways to optimize the code? Other feedback is also welcome!

``````bfs :: (a -> Bool) -- ^ Goal if evaluates to True
-> (a -> Bool) -- ^ Prune if evaluates to False
-> a  -- ^ Starting point of search
-> (a -> (a))  -- ^ Branches at a point
-> (a)  -- ^ Goals
bfs predicate prune a0 branch = filter predicate searchspace
where
-- An elegant solution
-- searchspace = a0 : (branch =<< searchspace)
-- However, this solution <<loop>>'s when the search is finite
searchspace = concat \$ takeWhile (not.null) epochs
epochs = (a0) : map (as -> ( a' | a <- as, prune a, a' <- branch a)) epochs
``````

## graphs – Edge exploration with spanning trees

Given an undirected connected graph $$G=(V,E)$$, is there a sequence of spanning trees $$T_0, dots, T_{|E|-|V|+1}$$ satisfying the following edge exchange property: $$forall i >0, T_i = T_{i-1} – (u, v) + (u, w)$$ with $$(v, w) in T_i$$, and such that the union of the spanning trees is equal to $$G$$?

If such sequence exists then it is minimal since $$T_0$$ covers $$|V| – 1$$ edges and each one of the following tree adds exactly one edge to the set of covered edges.
I am interested in the complexity of solving the problem for arbitrary graphs and in finding graph families for which this problem can be solved.

A first necessary condition is that $$G$$ must have a basis cycle composed solely of triangles. If there is a cycle in $$G$$ cannot be expressed as the symmetric difference of triangles then there is necessarily one edge that cannot be covered.

I’m struggling to get beyond that. Do you know of any related problem?

## A programming problem about node objects in trees

I want to create tree where each node knows its parent and children.

Then, maintain the parent and children member variables in the node, and make sure that they are consistent, i.e. that the parent and parent children lists change at the same time.

The current design node has both `set_parent` and `add_child`, so if the method is implemented literally, the synchronization problem is not easy to solve and needs to be remembered and managed by the user

To solve this problem, calling `set_parent` automatically calls the parent `add_child`, and when `add_child` is called, the parent of the child needs to be checked first, and an exception is thrown if the state is not uniform. This partially solves the problem.

To reduce complexity it would be better to expose only one of the two interface methods, how should I design it?

## Merging two B trees in O(h)

Given two B – trees A, B (from order of m) such thats: for each a in A and b in B: a > b
and also the number of elements in A is larger than the number of elements in B.

How can I merge them into one tree from the order of m, in O(h)
when “h” is the height of the A tree.

## data structures – What is the time complexity of comparing two Merkle trees?

I have a simple recursive function that compares two merkle trees and accumulates the differences in the leaf nodes. However, I am unable to measure the time complexity of it. Specifically, I would like to see how does it compare against comparing two Hashtables or two BSTs. A group of leaves is a `row` in this case and they share a `rowid`. In the code below I am just accumulating the differences at the leaf level.

``````def diff_helper(node1: MNode, node2: MNode, diff: List(Difference)):
if not node1 and not node2:
return
elif node1.rowid==node2.rowid and node1.signature==node2.signature and node1.nodetype==NodeType.Row and node2.nodetype==NodeType.Row:
return
elif node1.rowid==node2.rowid and node1.signature!=node2.signature and node1.nodetype==NodeType.Row and node2.nodetype==NodeType.Row:
diff_helper(node1.left, node2.left, diff)
diff_helper(node1.right, node2.right, diff)
elif node1.rowid==node2.rowid and node1.signature!=node2.signature and node1.nodetype==NodeType.Leaf and node2.nodetype==NodeType.Leaf:
diff.append(Difference(node1.rowid, node1.column, node1.value, node2.value))
else:
diff_helper(node1.left, node2.left, diff)
diff_helper(node1.right, node2.right, diff)

``````

Time complexity:

1. On the best case, I see that this is a constant operation since the root hashes of both trees would be the same.
2. On the worst case, the number of comparisons is the total number of all leaf nodes.

Question:

Assuming the above time complexity, it doesn’t seem to fare any better than comparing two Hashtables where each key is a rowid and the values being leaves. I understand that with Hashtable, once you find the values of the rowid, you’ll need to do a linear comparison of each leaf as compared to O(logm), m being the number of leaves under each row. How would you represent that in Big O terms?

## trees – Generic real-time message/event matching engine

I’m looking for methods (any kind of combinations of algorithms & corresponding data structures) that can be used as a generic matching engine in case of arbitrary message/event types. Let me formalize the problem a bit:

• Let $$C$$ denote a condition type consisting of an arbitrary data type (numeric values/strings/dates/enumerations/ranges/etc.)
and a compatible comparison operator: $$C = (text{Type}, text{Operator})$$. For
instance, in the case of numeric values, $$C_1 = (text{Integer}, <=)$$, or for strings $$C_2 = (text{String}, text{Contains})$$.

• The condition types can be instantiated with an actual reference value of the
condition’s underlying data type, for instance: $$c_1 = (text{Integer} = 5, <=)$$ or $$c_2 = (text{String} = text{“xy”}, text{Contains})$$.

• Obviously, multiple conditions can be combined which requires the
definition of a condition set $$S = (C_1, C_2, ldots, C_n)$$. A
concrete condition set can be e.g.: $$s = ((text{Real} = 3.14, >), (text{String} = text{“abc”}, text{!=}))$$. For simplicity, the
logical connection between the conditions of a set is always
$$text{AND}$$ (so in order for a set to be a match for an event, all
the conditions of $$s$$ must be met).

• Finally, multiple such condition sets can coexist which we can
visualize like the rows of a data table: $$t = {s_1, s_2, ldots, s_m}$$.

The use case would be that one assigns some operations/actions to the individual condition sets (rows) and executes only the operations whose conditions matched the properties of the incoming event in real-time (note that this is a difference compared against traditional filtering – we define the conditions first, then we wait for the data, and not the other way around). These properties must be identified in advance and they must correspond to the condition types of the given scenario (e.g., $$c_1 = (text{Integer} = 5, <=)$$ always uses the API `int EventT::get_some_field()` of the event type), however, such implementation details are not relevant from the core algorithmic problem’s point of view.

To sum up: the input of the algorithm (or matching engine) is $$(t, e)$$ where $$e$$ is a compatible event, while the output $$t’$$ is a subset of $$t$$ (the most complete possible) such that $$forall s in t’$$ it’s true that all conditions in $$s$$ matched $$e$$.

Let’s see a complete example, starting with $$t$$:

ID $$C_1$$ $$C_2$$
1 $$(text{Integer} = 66, =)$$ $$(text{String} = text{“*”}, =)$$
2 $$(text{Integer} = 50, > text{(greater than)})$$ $$(text{String} = text{“abc”}, text{!=})$$

A wildcard (see the first value in the $$C_2$$ column) basically means that we won’t utilize the 2nd condition (any string will match).

And now a couple of events:

• $$e_1 = (35, text{“xy”})$$ – won’t match any of the 2 condition sets,
• $$e_2 = (66, text{“abc”})$$ – will match only the 1st set,
• $$e_3 = (77, text{“def”})$$ – will match only the 2nd set,
• $$e_4 = (66, text{“xy”})$$ – will match both sets,
• $$e_5 = (88, text{“abc”})$$ – won’t match any of the 2 condition sets.

One possible way I can think of to implement this engine are trees: the levels of the tree represent the condition types (and on a particular level there are as many nodes as the number of rows in $$t$$), while the nodes the actual conditions, and whenever the conditions of all the nodes through a path in the tree till a leaf node (including the leaf node) are met, we have a match.

Other approaches are welcome, still, I’d appreciate concrete, possibly open-source implementations (with optimized/efficient underlying algorithms) even more. If there is a tree-based solution out somewhere, I’d be happy to take a look at it, too.

## c# – How to implement a chain of events on a tree’s CRUD operations?

I am working on a project in which I have a tree with 4 layers and the hierarchy is like this.
Customer -> Site -> Location -> Guardroom

In DB each entity has its own table and the child knows its parent’s Id.

``````public class Guardroom{
public int Id {get; set;}
public string Name {get; set;}
public int LocationId {get; set;}
}
``````

A rule is that guardroom should be the only leaf. What I mean is that

``````Customer must have at least one child (site)
|
|--> Site must have at least one child (location)
|
|--> Location must have at least one child (guardroom)
``````

My challenge is that if I delete a guardroom I must delete the location only if the guardroom has no siblings and the grandparent if location has no siblings and so on. In other words, If I delete the guardroom I must delete the nodes above in cascade only if the node to delete has only 1 child.

I do not want to have a highly coupled structure so I do not want the guardroom to know about the location. I was thinking in using events but I am not sure what patter or how to implement it.

My infrastructure looks like this.

I implemented dependency injection and Domain Driven Design. I have a service for each layer in the tree:
i.e.

``````public class GuardroomService: IGuardroomService {

//Here dependency is injected.
public GuardroomService(IGuardroomDataAccess guardroomService){
_guardroomService = guardroomService;
}

public void Delete(int guardroomId){
//Here I want to raise an event to notify parent (location) and take further action.
}

//...
//The remaining CRUD operations and functions.

}
``````

What patter/structure should I implement to let the other services I am deleting a child without allowing the same service to know about the other services.

Any help will be much appreciated. Thank you in advance.