how to select the first x elements in a binary search tree? - binary-search-tree

is there any existing algorithms for selecting the first x elements in a binary search tree? one way i could think of is to modify the tree traversal as follow:
int x = 0;
void inorder(tree* root, int *select_number, int *x){
if(root && select_number > x){
inorder(root->left, select_number,x);
//operations here
(*x)++;
inorder(root->right,select_number,x);
}
}
can this code work? is there a better way to do this? thank you so much!

Related

Binary search tree (BST) inorder visit that prints "The BST is in order"

I am currently working on a Binary Search Tree project, and I would like to implement an "inorder" visit function:
void inorder(struct node *root)
{
if(root!=NULL) // checking if the root is not null
{
inorder(root->left_child); // visiting left child
printf(" %d ", root->data); // printing data at root
inorder(root->right_child);// visiting right child
}
}
However I do have a little issue, my BST varies between 100000 and 1000000 keys, and as you can imagine, printing them all is not very "handy". Is there perhaps a way to modify this inorder function in a way that it only prints "The BST is in order"? I have been trying to implement it but I really can't find a solution.
Thanks in advance for your help! Wish you a lovely coding session!
It looks like you want to verify whether a tree is actually a valid BST, i.e. its in-order traversal would visit its values in non-decreasing order.
For that you need a different function. Here is how it could be done:
int isValidBstHelper(struct node *root, int low, int high) {
return root == NULL ||
(root->data >= low && root->data <= high &&
isValidBstHelper(root->left_child, low, root->data) &&
isValidBstHelper(root->right_child, root->data, high));
}
int isValidBst(struct node *root) {
return isValidBstHelper(root, INT_MIN, INT_MAX);
}
isValidBst will return 1 when the tree is a valid BST and 0 when it is not.
To print the result, just call like this:
if (isValidBst(root)) {
printf("The tree is a valid BST");
} else {
printf("The tree is NOT a valid BST");
}

VB.Net Search a string

I am searching a string of DNA chars, ATCG. I may wish to look for AT for example and the search must ignore ATAT not find two AT's. I need to know how many AT,s there are in the string and their position in there position.
I tried various ideas but so far have failed. I used Mid, Contains. If someone can give me a hint I would be grateful.
Regards
Not a VB.NET dude (C# is my current dope), but luckily they're similar. If you don't care about execution time, you can just brute force it. First, see if your pattern occurs in the string at all:
bool containsAT myDNAChars.Contains( "AT" );
Then you can go about finding their positions:
var myListOfMatches = new List<int>();
int searchIndex = 0;
string pattern = "AT";
bool done = false;
while( !done )
{
int atIndex = myDNAChars.IndexOf( pattern, searchIndex );
myListOfMatches.Add( atIndex );
searchIndex += pattern.Length;
if( searchIndex > myDNAChars.Length )
{
done = true;
}
}
Once you have a list of matches, you can iterate over it and discard any occurrences of "ATAT" or any other patterns you don't want.
It's not elegant--it's brute force--but it should work.
Sorry about the C#, but it should be easy to convert to VB.NET.

Optimized recalculating all pairs shortest path when removing vertexes dynamically from an undirected graph

I use following dijkstra implementation to calculate all pairs shortest paths in an undirected graph. After calling calculateAllPaths(), dist[i][j] contains shortest path length between i and j (or Integer.MAX_VALUE if no such path available).
The problem is that some vertexes of my graph are removing dynamically and I should recalculate all paths from scratch to update dist matrix. I'm seeking for a solution to optimize update speed by avoiding unnecessary calculations when a vertex removes from my graph. I already search for solution and I now there is some algorithms such as LPA* to do this, but they seem very complicated and I guess a simpler solution may solve my problem.
public static void calculateAllPaths()
{
for(int j=graph.length/2+graph.length%2;j>=0;j--)
{
calculateAllPathsFromSource(j);
}
}
public static void calculateAllPathsFromSource(int s)
{
final boolean visited[] = new boolean[graph.length];
for (int i=0; i<dist.length; i++)
{
if(i == s)
{
continue;
}
//visit next node
int next = -1;
int minDist = Integer.MAX_VALUE;
for (int j=0; j<dist[s].length; j++)
{
if (!visited[j] && dist[s][j] < minDist)
{
next = j;
minDist = dist[s][j];
}
}
if(next == -1)
{
continue;
}
visited[next] = true;
for(int v=0;v<graph.length;v++)
{
if(v == next || graph[next][v] == -1)
{
continue;
}
int md = dist[s][next] + graph[next][v];
if(md < dist[s][v])
{
dist[s][v] = dist[v][s] = md;
}
}
}
}
If you know that vertices are only being removed dynamically, then instead of just storing the best path matrix dist[i][j], you could also store the permutation of each such path. Say, instead of dist[i][j] you make a custom class myBestPathInfo, and the array of an instance of this, say myBestPathInfo[i][j], contain members best distance as well as permutation of the best path. Preferably, the best path permutation is described as an ordered set of some vertex objects, where the latter are of reference type and unique for each vertex (however used in several myBestPathInfo instances). Such objects could include a boolean property isActive (true/false).
Whenever a vertex is removed, you traverse through the best path permutations for each vertex-vertex pair, to make sure no vertex has been deactivated. Finally, only for broken paths (deactivated vertices) do you re-run Dijkstra's algorithm.
Another solution would be to solve the shortest path for all pairs using linear programming (LP) techniques. A removed vertex can be easily implemented as an additional constraint in your program (e.g. flow in <=0 and and flow out of vertex <= 0*), after which the re-solving of the shortest path LP:s can use the previous optimal solution as a feasible basic feasible solution (BFS) in the dual LPs. This property holds since adding a constraint in the primal LP is equivalent to an additional variable in the dual; hence, previously optimal primal BFS will be feasible in dual after additional constraints. (on-the-fly starting on simplex solver for LPs).

How to use CGAL Arrangement_2 zone?

Although there is some documentation related to the zone free function of Arrangement_2 module, it is not mentioned in any example files and the usage is not obvious.
Assuming that I have an arrangement of points and line segments based on CGAL::Arr_linear_traits_2, I want to print out all faces visited when walking along a given Segment_2. How can I do that?
You need to use the "assign" function:
void segment_intersect(Arrangement_2 &arr, Segment_2 &c)
{
std::vector<CGAL::Object> zone_elems;
Arrangement_2::Face_handle face;
CGAL::zone(arr, c, std::back_inserter(zone_elems));
for ( int i = 0; i < (int)zone_elems.size(); ++i )
{
if ( assign(face, zone_elems[i]) )
//print the face index...
}
}
The usage actually is quite obvious. To get all elements intersected, this code is enough:
void segment_intersect(Arrangement_2 &arr, Segment_2 &c)
{
std::vector<CGAL::Object> zone_elems;
CGAL::zone(arr, c, std::back_inserter(zone_elems));
}
I have yet to find out how to extract faces out of the vector.

Is there a less ugly way to do input in D than scanf()?

Currently the only way I know how to do input in D is with the scanf() function. But god damn it's ugly. You would think that since it's an upgrade from C that they would have fixed that.
I'm looking for a way to do it with a single argument. Currently you have to do:
int foo = 0;
scanf("%i", &foo);
writeln("%i", foo);
But it would look a lot cleaner with a single argument. Something like:
int foo = 0;
scanf(foo);
writeln(foo);
Thanks.
readf("%d", &foo); allows working with std.stdio.File rather than C FILE*
foo = readln().strip().to!int();
For reading entire files with lines formatted in the same way:
int[] numbers = slurp!int("filename", "%d");
There's a really cool user-input module here:
https://github.com/Abscissa/scriptlike/blob/master/src/scriptlike/interact.d
Example code:
if (userInput!bool("Do you want to continue?"))
{
auto outputFolder = pathLocation("Where you do want to place the output?");
auto color = menu!string("What color would you like to use?", ["Blue", "Green"]);
}
auto num = require!(int, "a > 0 && a <= 10")("Enter a number from 1 to 10");
The above answers are great. I just want to add my 2 cents.
I often have the following simple function lying around:
T read(T)()
{
T obj;
readf(" %s", &obj);
return obj;
}
It's generic and pretty handy - it swallows any white space and reads any type you ask. You can use it like this:
auto number = read!int;
auto floating_number = read!float;
// etc.