## list manipulation – How to construct a tree from a preorder traversal

The list

``````t1 = {1, 2, 3, 3, 4, 4, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 2};
``````

might be derived from a pre-order traversal of

``````tree1 = Tree[1, {Tree[2, {3, Tree[3, {4, 4}], 3, Tree[3, {4}], 3, 3}],
Tree[2, {Tree[3, {4}]}], Tree[2, {3}], 2}]
``````

But how to take the original list, `t1` here, and build the tree `tree1` ?

What have I tried so far ? Nothing to any avail! Well, that’s not quite true, I have made some progress with a very procedural code to walk along the list and try to figure out the structure of the tree as each new element is read, but I have a dispiriting feeling that I have missed an obvious usage of some of the smarter functional programming functionality.

## 8 – Why ConfigFormBase does not goes through custom construct() when using managed_file?

First I want to state that this is a question. My Form is working, but I had, strangely, to add clauses for the case when my `CustomForm` extending `ConfigFormBase` did not goes as expected throught the `__construct()`

I created a `config` property in the `__construct()`. Then, I could access it from any function, and it worked fine.

As soon as I added a `managed_file`, things went wrong. Specifically, `\$this->config` was `null` in `validateForm` and `submitForm`. I could restore the property easily by calling the factory again (and that’s what I end up doing), but I’m confused.

What I see is the `managed_file` module send the form in XHR when updating the `managed_file` input. So when I’m validating the form, maybe there is a cache version or something that gets loaded, or the `callback_func` works differently. Anyway, the `__construct()` is executed on the XHR request (I checked with xdebug) but not after when I’m (re) submitting the form with the button.

I compared the stack when \$this->config is null and when it’s not, and did not spot any difference.

Maybe it’s part of a multi-part Form functionality ?

I’m sure I’m getting it wrong somewhere.

``````  /**
* Constructs a DrupalsystemConfigFormBase object.
*
* @param DrupalCoreConfigConfigFactoryInterface \$config_factory
*   The factory for configuration objects.
*/
public function __construct(ConfigFactoryInterface \$config_factory) {
\$this->setConfigFactory(\$config_factory);
\$this->config = \$this->config('custom.settings');

parent::__construct(\$config_factory);
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface \$container) {
return new static(
\$container->get('config.factory'),
);

}

/**
* {@inheritdoc}
*/
public function buildForm(array \$form, FormStateInterface \$form_state): array {

\$form('section5')(self::TAB_IMAGE) = (
'#type' => 'managed_file',
'#title' => \$this->t("Image de l'onglet"),
'#default_value' => (\$this->config->get(self::TAB_IMAGE)) ? (\$this->config->get(self::TAB_IMAGE)) : NULL,
'file_validate_extensions' => ('gif png jpg jpeg'),
'file_validate_image_resolution' => ('300x300'),
),
);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &\$form, FormStateInterface \$form_state) {
// When submitting a Form with managed_file, weirdly no __construct().
if (!\$this->config) {
\$this->config = \$this->config('custom.settings');
}
``````

## computational geometry – Algorithm to construct a parabola that hits a given target and avoids given boundaries

I’m working on a video game and I’m struggling with the math behind one of the enemies. The enemy is a grenade launcher mounted on a vertical rail, which can slide up and down, and lob a grenade at any angle with any amount of force. The grenade’s path will be a parabola which must hit the player, but there are line segment boundaries in the way represented by their two endpoints which the parabola must avoid.

Here is a drawing.

What I’d like to do is calculate the equation for the parabola of the grenade which hits a target and misses all of the boundaries, from which I can figure out the position, angle, and force for the launcher to use. The parabola must be subject to these three constraints:

1. The parabola must pass through the target point $$(x_T, y_T)$$
2. The parabola must pass through the line segment $$overline{RS}$$
3. For each boundary $$overline{EF}$$, if the parabola passes through the segment, it must not happen between the line $$overline{RS}$$ and the target point.

Depending on where the target is, there may be no solution, in which case I’d like it to return that information. If there is any solution there will be multiple; I would only need one.

## What I’ve tried so far:

We can represent the parabola as $$y-y_T=A(x-x_T)^2+B(x-x_T)$$, which takes care of the first constraint, and means we need to find values for $$A$$ and $$B$$ that satisfy the other two constraints (we know $$A$$ must be negative because of the direction of gravity). Then for each boundary $$overline{EF}$$ on the map, with endpoints $$(x_E,y_E)$$ and $$(x_F,y_F)$$, we can represent the boundary line as $$(y_E-y_F)x+(x_F-x_E)y+(x_E y_F-x_F y_E)=0$$. From that I can find the points of intersection between the line and the parabola, and make sure that for every boundary, the x-values of the points are either not between $$x_E$$ and $$x_F$$, or they are not between $$x_S$$ and $$x_T$$. This quickly becomes a nasty quadratic equation, which then creates a system of linear inequalities that I don’t know how to solve. Can anyone think of a better way to approach the problem?

## mathematics – How to construct a matrix with the following mapping

How would I create a matrix that maps coordinates like so:

Near plane

``````x: (-3,3) -> (-1,1)
y: (-6,2) -> (-1,1)
z: 2 -> -1
``````

Far plane

``````x: (-4,4) -> (-1,1)
y: (-4,4) -> (-1,1)
z: 0 -> 1
``````

Visual

Result:

My current solution is a transformation in a vertex shader like below, but if it’s possible to use a matrix I can keep my shaders as is.

``````vec4 special_projection(vec4 p){
float ty = 0.25 * p.z;
float tx = 0.25 * p.x;
float xz = (tx / 3.0) * (p.z / 2.0);
float x = tx + xz;
float y = 0.25 * p.y + ty;
float z = -0.5 * p.z;
return vec4(x,y,z,1);
}
``````

## path finding – Construct flow field cost map from polygon geometry

I’m looking into implementing flow fields for pathing large numbers of units across a map. From what I can find, flow fields are always constructed as a grid, and require building a cost map of obstacles and terrain levels.

Assuming I start with map geometry (not a grid), this would seem to mean that I would need some way of rasterizing my map polygons into the cost map.

But is rasterization the best way to accomplish this? I’m assuming this is a solved problem, but have been unsuccessful in finding other options.

## graph theory – Construct By Compactness (Pentagonal Tiling – Rao paper)

In the (arxiv) paper, Exhaustive search of convex pentagons which tile the plane, on page 4 under the proof of Lemma 2, it is said that:

“… We keep a connected component $$H_d’$$ of $$H_{d}$$ such that $$S(H_{d}’)$$ contains the centre of the square. Then one can construct by compactness an infinite graph in which every vertex is an interior vertex, and with $$W(G’) underline{subset} W(T)-{v}$$. There are three cases: either $$G’$$ corresponds to a tiling of the plane, of a half plane or of a stripe. In all cases, one can construct a tiling of the place without vertex of vector type $$v$$, and no new vector type.”

Searching “construct by compactness” yields very few results, and each result is equally vague about what this means. It seems as if there is some “well known” procedure which the author is alluding to, but I have no idea what it is. Any suggestions will be appreciated.

I’m happy to update this question with pertinent details about the preceding content of the paper, but I’m not sure which details will be relevant, so for now I want to keep this question brief.

## ag.algebraic geometry – Given a fixed point \$x\$, want to construct a system of multivariate polynomial that has \$x\$ as the only solution

Suppose I am given a point $$x=(alpha_1, alpha_2, alpha_3)in mathbb{F}_q^3$$. I want to construct a system of multivariate non linear polynomial that has $$x$$ as the only solution. Is that possible?

Can some one please give some hints or mention some references?

## godot – Traversing an acyclic binary tree to construct paths from a given starting node, but the paths come out wrong

The tree is an acyclic binary tree. It’s composed of node objects that have a list of connections to link objects (at most 3), and link objects that have a list of connections to node objects (always 2). I am trying to construct a list of possible paths to other nodes that can be reached given a fuel budget and a fuel cost on each link. What it is supposed to do is go through each non-backtracking connection of a node, and spawn a new route and thread to investigate that, leaving the current one to end at that node and thus create a list of routes to every node in the reachable area. When executed, the list of end destinations are valid but many of the paths that are constructed to get to them are wrong, going down other branches in the tree that are extraneous or entirely outside of the reachable area bounded by the fuel budget as well as jumping between nodes that aren’t directly connected. There seems to be some pattern in the errors, when going down from the root of some branches of the tree the path goes down every offshoot in order first instead of going in a straight line, and when going up the tree the path tends to go further out and make triangle shapes, often landing somewhere other than the listed destination. I have already checked the link and node connections themselves to see if they are assigned properly, and they are. What am I getting wrong?

Route class definition

``````var origin:Node
var destination:Node
var totaldV:float
var totalt:float
var dVBudget:float
var tBudget:float
var tdVRatio:float
var nodes:Array

func duplicate_values(originator:Route):
origin = originator.origin
destination = originator.destination
totaldV = originator.totaldV
totalt = originator.totalt
dVBudget = originator.dVBudget
tBudget = originator.tBudget
tdVRatio = originator.tdVRatio
nodes = originator.nodes

func _init(originator_route):
if originator_route != null:
duplicate_values(originator_route)
``````

Tree traversal algorithm

``````var routes:Array

func traverse(current_node:Node, previous_route:Route):
if previous_route == null:                             # Starts off the recursion by providing an initial node
previous_route = Route.new(null)
previous_route.origin = current_node
previous_route.nodes.append(previous_route.origin)
previous_route.dVBudget = 2000
previous_route.totaldV = 0
if (previous_route.totaldV + link.dV < previous_route.dVBudget &&
!IsBacktracking(previous_route, LinkDestination(link, current_node))):   # If there is enough fuel and the link isn't backtracking, go through it.
var working_route:Route = Route.new(previous_route)    # Copy the previous route to make the new route
routes.append(working_route)
working_route.nodes.append(working_route.destination)
traverse(working_route.destination, working_route)
DisplayRoutes()
root.get_parent().pathSelectionFlag = true   # UI control boolean

func IsBacktracking(route:Route, destinationNode:Node) -> bool:
for nodeI in route.nodes:
if (destinationNode == nodeI):
return true
return false

if (nodeI != originNode):
return nodeI
return originNode
``````

## context free – Eliminating left recursion using a loop construct

I’m trying to merge a little bit of theory with a little bit of practice. I’m writing a parser-generator that generates a top-down parser based on a given grammar.

I’d like to handle left- and right recursion properly, so they would each yield the “left-recursive” and “right-recursive” tree respectively (I’m not sure if left- and rightmost derivative would be a correct term here, that would mean the whole tree). This is very important for PEG, where the associativity and order of operations is encoded in the tree. The problem is that top-down parsers can’t deal with left-recursion directly.

I know the elimination rule for left-recursion, which is given a rule in the form

$$A rightarrow A alpha_1 | dots | A alpha_n | beta_1 | dots | beta_m$$

We can rewrite it into right-recursion using the following 2 rules:

$$A rightarrow beta_1 A’ | dots | beta_m A’ \ A’ rightarrow alpha_1 A’ | dots | alpha_n A’ | varepsilon$$

This is fine for the “formal” part, but the grammar became right-recursive. To me this rule seems like it’s just using right-recursion to essentially loop parts of the grammar.

So my idea was to introduce a looping construct that would account for folding the tree left. If I introduce a new postfix operator `*` that would mean repeating the construct 0 or more times, would the following also be a valid equivalent left-recursion elimination for A?

$$A rightarrow (beta_1 | dots | beta_m) (alpha_1 | dots | alpha_n)^*$$

Note that since the repetition can occur 0 times, this should account for the “epsilon-case” too.

I have a strong suspicion that this is equivalent, as I did something very similar when manually parsing left-associative operators in math expressions. I’d like confirmation before introducing it in a general tool.