BST with duplicates(RABPAB) - binary-search-tree

I wanted to create a BST for the string "RABSAB".
The rules for inserting into the tree are:
1) left subtree of a node < the node's key.
2) right subtree of a node >= the node's key.
i ended up with two answers:
R R
/ \ / \
A S A S
\ \
A B
\ /
B A
\ \
B B
Which one among them is correct?

I think it should be something like
R
/ \
A S
\
B
/
A
\
B
this way you would instead have a trie instead of a tree

Related

How to use property value to filter out vertices?

I'm trying to filter out vertices to which distance from given latitude and longitude is above max distance stored as vertex property and retrieve the ones that are not filtered.
I used code from Kelvin Lawrence's book to calculate the distance using the Haversine Great Circle Distance formula. The thing is, if I pass an integer value to lte everything seems to be working fine, but I need to feed it with each traversed vertex property value.
Code:
r_deg = 0.017453293
e_rad = 6371
def get_points_within_distance(latitude, longitude, r_deg, e_rad):
try:
_result = n_graph. \
with_side_effect("r_deg", r_deg). \
with_side_effect("e_rad", e_rad). \
with_side_effect("p_lat", latitude). \
with_side_effect("p_lon", longitude). \
V(). \
hasLabel("point"). \
where(
project("ladiff", "lodiff", "latitude", "longitude").
by(project("lat").by("latitude").
math("(lat - p_lat) * r_deg")).
by(project("lon").by("longitude").
math("(lon - p_lon) * r_deg")).
by("latitude").
by("longitude").
math('(sin(ladiff/2))^2 + cos(latitude*r_deg) * cos(p_lat*r_deg) * (sin(lodiff/2))^2').
math('e_rad * (2 * asin(sqrt(_)))').
is_(lte(10))
). \
value_map(True). \
to_list()
except Exception as _e:
LOG.error(f"Failed to retrieve points: {_e}.")
return
return _result
Each vertex has three properties:
latitude
longitude
max_distance
What I'm trying to achieve is to pass max_distance value instead of 10.
You'll need to use the where()-by() approach here. Instead of using the where() as part of the calculation, we'll use an as() label to bookmark our starting vertex. Then perform the distance calculation and use the where()-by() to filter. After the where()-by(), we'll refer back to the starting vertex via a select() on the label for the traversals that passed the filter.
n_graph.
with_side_effect("r_deg", r_deg).
with_side_effect("e_rad", e_rad).
with_side_effect("p_lat", latitude).
with_side_effect("p_lon", longitude).
V().
hasLabel("point").
as("startPoint").
project("ladiff", "lodiff", "latitude", "longitude").
by(project("lat").by("latitude").
math("(lat - p_lat) * r_deg")).
by(project("lon").by("longitude").
math("(lon - p_lon) * r_deg")).
by("latitude").
by("longitude").
math('(sin(ladiff/2))^2 + cos(latitude*r_deg) * cos(p_lat*r_deg) * (sin(lodiff/2))^2').
math('e_rad * (2 * asin(sqrt(_)))').
where(lte("startPoint")).by().by("max_distance").
select("startPoint").
value_map(True).
to_list()

How to fix "LoadError: DimensionMismatch ("cannot broadcast array to have fewer dimensions")"

I'd like to solve the following two coupled differential equations numerically:
d/dt Phi_i = 1 - 1/N * \sum_{j=1}^N( k_{ij} sin(Phi_i - Phi_j + a)
d/dt k_{ij} = - epsilon * (sin(Phi_i - Phi_j + b) + k_{ij}
with defined starting conditions phi_0 (1-dim array with N entries) and k_0 (2-dim array with NxN entries)
I tried this: Using DifferentialEquations.js, build a matrix of initial starting conditions u0 = hcat(Phi_0, k_0) (2-dim array, Nx(N+1)), and somehow define that the first equation applies to to first column (in my code [:,1]) , and the second equation applies to the other columns (in my code [:,2:N+1]).
using Distributions
using DifferentialEquations
N = 100
phi0 = rand(N)*2*pi
k0 = rand(Uniform(-1,1), N,N)
function dynamics(du, u, p, t)
a = 0.3*pi
b = -0.53*pi
epsi = 0.01
du[:,1] .= 1 .- 1/N .* sum.([u[i,j+1] * sin(u[i,1] - u[j,1] + a) for i in 1:N, j in 1:N], dims=2)
du[:,2:N+1] .= .- epsi .* [sin(u[i,1] - u[j,1] + b) + u[i,j+1] for i in 1:N, j in 1:N]
end
u0 = hcat(phi0, k0)
tspan = (0.0, 200.0)
prob = ODEProblem(dynamics, u0, tspan)
sol = solve(prob)
Running this lines of code result in this error:
LoadError: DimensionMismatch ("cannot broadcast array to have fewer dimensions")in expression starting at line 47 (which is sol = solve(prob))
I'm new to Julia, and I'm not sure if im heading in the right direction with this. Please help me!
First of all, edit the first package, which is Distributions and not Distribution, it took me a while to find the error xD
The main problem is the .= in your first equation. When you do that, you don't just assign new values to an array, you're making a view. I cannot explain you exactly what is a view, but what I can tell you is that, when you this kind of assign, the left and right side must have the same type.
For example:
N = 100
u = rand(N,N+1)
du = rand(N,N+1)
julia> u[:,1] .= du[:,1]
100-element view(::Array{Float64,2}, :, 1) with eltype Float64:
0.2948248997313967
0.2152933893895821
0.09114453738716022
0.35018616658607926
0.7788869975259098
0.2833659299216609
0.9093344091412392
...
The result is a view and not a Vector. With this syntax, left and right sides must have same type, and that does not happen in your example. Note that the types of rand(5) and rand(5,1) are different in Julia: the first is an Array{Float64,1} and the other is Array{Float64,2}. In your code, d[:,1] is an Array{Float64,1} but 1 .- 1/N .* sum.([u[i,j+1] * sin(u[i,1] - u[j,1] + a) for i in 1:N, j in 1:N], dims=2) is an Array{Float64,2}, that's why it doesn't work. You have two choices, change the equal sign for:
du[:,1] = ...
Or:
du[:,1] .= 1 .- 1/N .* sum.([u[i,j+1] * sin(u[i,1] - u[j,1] + a) for i in 1:N, j in 1:N], dims=2)[:,1]
The first choice is just a basic assign, the second choice uses the view way and matches the types of both sides.

Find predecessors in a BinaryTree in O(1)

I've been having trouble with the following question
I have a given Binary Tree (not necessarily BST) and two pointers (x,y) and I need to find if X is Y's predecessor in a O(1) complexity, I can add as many fields as I want.
I was thinking about adding each predecessor as a field as I insert the next child to the tree but in that way how can I search if X is Y's predecessor in O(1) complexity.
If you use nodes, add an unsigned int field, call it L, starting at 1 with root.
When you recursively insert, take the value of the previous node and multiply by 2 then add 1 if you go right, or simply multiply by 2 if you go left.
You will get a tree of L values that looks like this:
1
/ \
/ \
/ \
/ \
10 11
/ \ / \
/ \ / \
100 101 110 111
\ / \
1001 1110 1111
/
10010
An ancestor P should have a value P.L such that P.L is a substring of C.L and the number of bits in P.L is strictly less than the bits in C.L.
The tree's L values in base-10 is:
1
/ \
/ \
/ \
/ \
2 3
/ \ / \
/ \ / \
4 5 6 7
\ / \
9 14 15
/
18
If you have both pointers, if you take log_2(L), You will get the # of bits in that number L, which if you notice, represents the level in the tree you are at.
So if:
// Parent (ancestor) has equal or more bits?
if (log(P.L) >= log(C.L)) {
// parent is not an ancestor because it
// is either lower in tree, or at same level
}
If that check passes, Subtract bits(P) from bits(C), this will tell you how many more bits C.L has than P.L. Or, how many levels C is lower than P.
int D = log(C.L) - log(P.L)
Since C is lower, and all we did to calculate C.L value was multiply parent' L values by two (shift left) some number of times, if we were to shift C back over to the right (divide by 2) D times, the first D bits should match.
// Divide by 2, D times
int c = C.L >> D
// Is P.L a substring of C.L?
if (c == P.L) {
// P.L is a substring of C.L
// means P is an ancestor of C
}
// If we get here, C is below P in the tree, but C
// is not in a subtree of P because the first `D bits don't match`
In essence, we use integers as strings to keep track of the path of insertion, and we use bit manipulation to check if C.L is a substring of P.L in constant time.
Note, if you used an array, then P.L and C.L are simply the indexes of the nodes you would like to check.

The Knapsack Max Profit

There are 4 items: A weights 2LB has profit $40, B weights 5LB has profit $30, C weights 10LB has profit $50, and D weights 5LB has profit $10. Compute the maximum total profit you can take from any of the 4 items with a knapsack weight 16LB. You cannot take any portions of an item but the whole.
Please show how can the above problem be solved using knapsack problem approach.
A simple solution is to consider all subsets of items and calculate the total weight and value of all subsets. Then you should consider taking only the subsets that weighs less or equal to the capacity of your knapsack. From all such subsets, pick the maximum value subset.
To consider all subsets of items, there can be two cases for every item:
the item is included in the optimal subset,
the item is not included in the optimal subset.
Let's say the capacity of your knapsack is W. Therefore, the maximum value that can be obtained from n items is max of following two values.
Maximum value obtained by n-1 items and W weight (excluding the nth item)
Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nth item (including nth item).
If weight of the nth item is greater than W, then the nth item can't be included and case 1 is the only option. This would be a naive approach and the solution would take 2n time.
Now for the overlapping subproblem:
weight = {2, 5, 10, 5}
Capacity = 16
The recursion tree would look like:
// Here n,k -> items remaining, capacity remaining
// Going to left child -> including the item at hand
// Going to right child -> excluding the item at hand
_______4,16______
/ \
/ \
3,14 3,16
/ \ / \
/ \ / \
2,9 2,14 2,5 2,16
\ / \ \ / \
\ / \ \ / \__
1,9 1,4 1,14 1,5 1,6 1,16
/\ /\ /\ /\ / \
/ \ / \ / \ / \ / \
0,4 0,9 0,9 0,14 0,0 0,0 0,1 0,6 0,11 0,16
Since there are overlapping subproblems in the leaf, we can solve it using dynamic programming. If you store the values, it will be efficient to use them later. Here the match occurs in leaf nodes, if you take other examples, you'll see a match can occur far before the leaf nodes.
The pseudo-code would look like:
Procedure Knapsack(n, W): //here, n = number of items, W = capacity of Knapsack
for i from 0 up to n
for j from 0 up to W
if i == 0 or j == 0
table[i][j] :=0
else if weight[i-1] <= j
table[i][j] := max(profit[i-1] + table[i-1][w-weight[i-1]], table[i-1][j])
else
table[i][j] := table[i-1][j]
end if
end for
end for
Return table[n][W]

In csh, why does 4 - 3 + 1 == 0?

#!/bin/csh
# cows = 4 - 3 + 1
echo $cows
This simple csh script when run produces "0" for output when I'd expect "2".
~root: csh simple.1
0
I did a bunch of looking and the only thing I could think of was that the "-" was being read as a unary negation rather than subtraction, therefore changing operator precedence and ending up with 4 - 4 rather than 2 + 1. Is this correct? If so, any reason why? If not...help!
Edit: So they're right associative! These operators are NOT right associative in C, are they? Is C-Shell that different from C?
While you are expecting the operators to be left associative, they are right associative in csh, so it's evaluated as 4-(3+1)
-
/ \
/ \
4 +
/ \
3 1
The + and - operators are right-associative in csh. This means that '4 - 3 + 1' is evaluated as '4 - (3 + 1)'.
Operator grouping. It's reading the operation as 4 - (3 + 1), as opposed to (4 - 3) + 1.