How to find nodes value is greater than a specified value in a binary search tree - binary-search

I have a red black tree and the basic operations insert, delete, traversing inorder, postorder and preorder etc.
I wish to create a method that can return the nodes in the tree that are greater than a specified value. Same with less than too.
Can anyone point me to some pseudocode / algorithm (they probably mean the same thing)
Cheers

Below is the code I have created which tests fine for displaying my nodes in ascending order for nodes greater than or equal to a specified value. Can someone please review my code and recommend improvements and if possible recommend how I may do this for my LessThan method. Currently my LessThan method returns in descending order and I just can not see how to get it ascending. Cheers.
// --------------------------------------------------------------------------------
// GetNodesGreaterThan
// --------------------------------------------------------------------------------
/** \fn void RedBlackTree<T>::GetNodesGreaterThan(T &data)
* \brief This method checks to see if tree is empty otherwise calls the
* recursive the GreaterThan method.
* \param templated
* \return void
*/
template <class T>
void RedBlackTree<T>::GetNodesGreaterThan(T &data)
{
GreaterThan(m_root, data);
}
// --------------------------------------------------------------------------------
// GreaterThan
// --------------------------------------------------------------------------------
/** \fn void RedBlackTree<T>::GreaterThan(NodeType<T> *p, const T &data) const
* \brief This method finds the nodes in the tree that are greater than or equal to
* a specified value and puts nodes into a list.
* \param templated pointer
* \param constant template
* \return void
*/
template <class T>
void RedBlackTree<T>::GreaterThan(NodeType<T> *p, const T &data) const
{
if ( p != NULL) // we have hit a leaf node
{
if ((p->m_data == data) || (data < p->m_data)){ // record the node whos value is
GreaterThan(p->m_lLink, data); // move down left link
//cout << p->m_data << " "; // Display data (debug purpose)
}
GreaterThan(p->m_rLink, data); // move down right link
}
}
// --------------------------------------------------------------------------------
// GetNodesLessThan
// --------------------------------------------------------------------------------
/** \fn void RedBlackTree<T>::GetNodesLessThan(T &data)
* \brief This method checks to see if tree is empty otherwise calls the
* recursive the LessThan method.
* \param template
* \return void
*/
template <class T>
void RedBlackTree<T>::GetNodesLessThan(T &data)
{
ClearList(); // clears the node list
LessThan(m_root, data);
}
// --------------------------------------------------------------------------------
// LessThan
// --------------------------------------------------------------------------------
/** \fn void RedBlackTree<T>::LessThan(NodeType<T> *p, const T &data) const
* \brief This method finds the nodes in the tree that are less than or equal to
* a specified value and puts nodes into a list.
* \param templated pointer
* \param constant template
*/
template <class T>
void RedBlackTree<T>::LessThan(NodeType<T> *p, const T &data) const
{
if ( p != NULL)
{
if ((p->m_data == data) || (data > p->m_data)){ // record the node whos value is
LessThan(p->m_rLink, data); // move down left link
//cout << p->m_data << " "; // Display data (debug purpose)
//m_list[m_countOfElements] = p->m_data; // add to list
//m_countOfElements++; // increment # of elements
}
LessThan(p->m_lLink, data); // move down left link
}
}

Related

Error "Out of segment space" in VMEmulator cause by a getter mwthod in Jack

I am doing a project for nand2tetris. We write a program in Jack and test it on VMEmulator. The class looks like this:
class List {
field int data;
field List next;
/* Creates a new List object. */
constructor List new(int car, List cdr) {
let data = car;
let next = cdr;
return this;
}
/* Disposes this List by recursively disposing its tail. */
method void dispose() {
if (~(next = null)) {
do next.dispose();
}
// Use an OS routine to recycle the memory held by this object.
do Memory.deAlloc(this);
return;
}
/* Prints the list*/
method void print() {
do Output.printString(" -> ");
do Output.printInt(data);
if (~(next = null)) {
do next.print();
}
return;
}
/* Inserts the argument in the right position of the list (ascending order)*/
method void insertInOrder(int ins){
var List prev, curr, insert;
let prev = this;
let curr = prev.getnext();
while (ins > prev.getdata()){
if (ins < curr.getdata()){
let insert = List.new(ins, curr);
do prev.setnext(insert);
}
else{
let prev = prev.getnext();
let curr = prev.getnext();
}
}
return;
}
/* Searches the argument in the list, if found, it returns the corresponding List object*/
method List find(int toFind){
var List temp;
var List equal;
var boolean found;
let temp = this;
let found = false;
while (~(next = null)){
if(toFind = temp.getdata()){
let equal = temp;
let found = true;
}
let temp = temp.getnext();
}
if (found){
return equal;
}
else{
return null;
}
}
method List getnext(){
return next;
}
method void setnext(List object){
let next = object;
return;
}
method int getdata(){
return data;
}
}
It has one private variable data and a pointer next. So I wrote getter and setter method to return those values. Other methods are fine only the getdata()method is incorrect. When it runs through the VMEmulator, it shows the error Out of segment space in List.getdata.3. This shows in the VMEmulator.
0function List.getdata0
1push argument0
2pop pointer0
3push this 0
4return
the error is at the 4th line return. When I change the Jack code, the same error is still at the 4th line.
What exactly is the problem in my getter method?
When you run a VM program on the VMEmulator you must first manually set the pointers to the various segments, otherwise you may get an "Out of segment space" error.
To understand the necessary settings, look at what the corresponding .tst file does. An alternative method is to insert the proposed code inside a function, since the function call automatically makes this type of setting.
You can get this error when you try to access member data of an object which is not constructed. Could it be that the List cdr in the constructor was not properly constructed?

If statement in for loop not filtering out items in solidity

// #param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
// #return _id - list of ids for homes
function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
uint [] results;
for(uint i = 0 ; i<homes.length; i++) {
if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
results.push(homes[i].id);
}
}
return results;
}
The result is supposed to be a list of ids which match the physical address entered however it does not filter through but returns all the available homes.
When I change to using String utils nothing changes.
Here is the whole code:
pragma solidity ^0.4.0;
import "browser/StringUtils.sol";
// #title HomeListing
contract HomeListing {
struct Home {
uint id;
string physicalAddress;
bool available;
}
Home[] public homes;
mapping (address => Home) hostToHome;
event HomeEvent(uint _id);
event Test(uint length);
constructor() {
}
// #param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
function addHome(string _physicalAddress) public {
uint _id = uint(keccak256(_physicalAddress, msg.sender));
homes.push(Home(_id, _physicalAddress, true));
}
// #param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
// #return _id - list of ids for homes
function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
uint [] results;
for(uint i = 0 ; i<homes.length; i++) {
string location = homes[i].physicalAddress;
if(StringUtils.equal(location,_physicalAddress )) {
results.push(homes[i].id);
}
}
return results;
}
}
The part giving you trouble is the line uint[] results;. Arrays declared as local variables reference storage memory by default. From the "What is the memory keyword" section of the Solidity docs:
There are defaults for the storage location depending on which type of variable it concerns:
state variables are always in storage
function arguments are in memory by default
local variables of struct, array or mapping type reference storage by default
local variables of value type (i.e. neither array, nor struct nor mapping) are stored in the stack
The result is you're referencing the first storage slot of your contract, which happens to be Home[] public homes. That's why you're getting the entire array back.
To fix the problem, you need to use a memory array. However, you have an additional problem in that you can't use dynamic memory arrays in Solidity. A workaround is to decide on a result size limit and declare your array statically.
Example (limited to 10 results):
function listHomesByAddress(string _physicalAddress) public view returns(uint[10]) {
uint [10] memory results;
uint j = 0;
for(uint i = 0 ; i<homes.length && j < 10; i++) {
if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
results[j++] = homes[i].id;
}
}
return results;
}

Is there a way to generate 2D stretched mesh using CGAL?

I currently use CGAL to generate 2D Delaunay triangulation.One of the mesh control parameter is the maximum length of the triangle edge. The examples suggests that this parameter is a constant. I would like to know how this parameter be made function of some thing else, for example spatial location.
I think Delaunay meshing with variable density is not directly supported by CGAL although you could mesh your regions independently. Alternatively you may have a look at: http://www.geom.at/advanced-mesh-generation/ where I have implemented that as a callback function.
It doesn't look like CGAL provides an example of this but they machinery is all there. The details get a little complicated since the objects that control if triangles need to be refined also have to understand the priority under which triangles get refined.
To do this, I copied Delaunay_mesh_size_criteria_2 to create a new class (Delaunay_mesh_user_criteria_2) that has a spatially varying sizing field. Buried in the class is a function (user_sizing_field) that can be implemented with a varying size field based on location. The code below compares the size of the longest edge of the triangle to the minimum of the sizing field at the three vertices, but you could use a size at the barycenter or circumcenter or even send the entire triangle to the sizing function if you have a good way to compute the smallest allowable size on the triangle altogether.
This is a starting point, although a better solution would,
refactor some things to avoid so much duplication with with existing Delaunay_mesh_size_criteria,
allow the user to pass in the sizing function as an argument to the criteria object, and
be shipped with CGAL.
template <class CDT>
class Delaunay_mesh_user_criteria_2 :
public virtual Delaunay_mesh_criteria_2<CDT>
{
protected:
typedef typename CDT::Geom_traits Geom_traits;
double sizebound;
public:
typedef Delaunay_mesh_criteria_2<CDT> Base;
Delaunay_mesh_user_criteria_2(const double aspect_bound = 0.125,
const Geom_traits& traits = Geom_traits())
: Base(aspect_bound, traits){}
// first: squared_minimum_sine
// second: size
struct Quality : public std::pair<double, double>
{
typedef std::pair<double, double> Base;
Quality() : Base() {};
Quality(double _sine, double _size) : Base(_sine, _size) {}
const double& size() const { return second; }
const double& sine() const { return first; }
// q1<q2 means q1 is prioritised over q2
// ( q1 == *this, q2 == q )
bool operator<(const Quality& q) const
{
if( size() > 1 )
if( q.size() > 1 )
return ( size() > q.size() );
else
return true; // *this is big but not q
else
if( q.size() > 1 )
return false; // q is big but not *this
return( sine() < q.sine() );
}
std::ostream& operator<<(std::ostream& out) const
{
return out << "(size=" << size()
<< ", sine=" << sine() << ")";
}
};
class Is_bad: public Base::Is_bad
{
public:
typedef typename Base::Is_bad::Point_2 Point_2;
Is_bad(const double aspect_bound,
const Geom_traits& traits)
: Base::Is_bad(aspect_bound, traits) {}
Mesh_2::Face_badness operator()(const Quality q) const
{
if( q.size() > 1 )
return Mesh_2::IMPERATIVELY_BAD;
if( q.sine() < this->B )
return Mesh_2::BAD;
else
return Mesh_2::NOT_BAD;
}
double user_sizing_function(const Point_2 p) const
{
// IMPLEMENT YOUR CUSTOM SIZING FUNCTION HERE.
// BUT MAKE SURE THIS RETURNS SOMETHING LARGER
// THAN ZERO TO ALLOW THE ALGORITHM TO TERMINATE
return std::abs(p.x()) + .025;
}
Mesh_2::Face_badness operator()(const typename CDT::Face_handle& fh,
Quality& q) const
{
typedef typename CDT::Geom_traits Geom_traits;
typedef typename Geom_traits::Compute_area_2 Compute_area_2;
typedef typename Geom_traits::Compute_squared_distance_2 Compute_squared_distance_2;
Geom_traits traits; /** #warning traits with data!! */
Compute_squared_distance_2 squared_distance =
traits.compute_squared_distance_2_object();
const Point_2& pa = fh->vertex(0)->point();
const Point_2& pb = fh->vertex(1)->point();
const Point_2& pc = fh->vertex(2)->point();
double size_bound = std::min(std::min(user_sizing_function(pa),
user_sizing_function(pb)),
user_sizing_function(pc));
double
a = CGAL::to_double(squared_distance(pb, pc)),
b = CGAL::to_double(squared_distance(pc, pa)),
c = CGAL::to_double(squared_distance(pa, pb));
double max_sq_length; // squared max edge length
double second_max_sq_length;
if(a<b)
{
if(b<c) {
max_sq_length = c;
second_max_sq_length = b;
}
else { // c<=b
max_sq_length = b;
second_max_sq_length = ( a < c ? c : a );
}
}
else // b<=a
{
if(a<c) {
max_sq_length = c;
second_max_sq_length = a;
}
else { // c<=a
max_sq_length = a;
second_max_sq_length = ( b < c ? c : b );
}
}
q.second = 0;
q.second = max_sq_length / (size_bound*size_bound);
// normalized by size bound to deal
// with size field
if( q.size() > 1 )
{
q.first = 1; // (do not compute sine)
return Mesh_2::IMPERATIVELY_BAD;
}
Compute_area_2 area_2 = traits.compute_area_2_object();
double area = 2*CGAL::to_double(area_2(pa, pb, pc));
q.first = (area * area) / (max_sq_length * second_max_sq_length); // (sine)
if( q.sine() < this->B )
return Mesh_2::BAD;
else
return Mesh_2::NOT_BAD;
}
};
Is_bad is_bad_object() const
{ return Is_bad(this->bound(), this->traits /* from the bad class */); }
};
I am also interested for variable mesh criteria on the domaine with CGAL. I have found an alternative many years ago : https://www.cs.cmu.edu/~quake/triangle.html
But i am still interested to do the same things with CGAL ... I don't know if it is possible ...

how to print all the vxWorks wvEvents

Is there a vxWorks command that lists all the wv events that are compiled in the code. I am trying to segregate all the events on one of our products which uses vxWorks 6.5.
No there isn't a command giving you a list of WindView events of your code.
Why don't you search for all lines containing wvEvent of all your source files and remove the duplicates? This should produce a list of all events...
--- Update ---
I've written the following small library to hook symbols within the VxWorks symbol table. This can be used to hook system calls within applications loaded after a symbol was hooked.
The following mechanism works since the ld command resolves all unresolved references of the application using the system symbol table (e.g. calls to printf are replaced with the value of the symbol printf which is the address of the printf implementation).
Here is the code of the library:
#include <vxWorks.h>
#include <symLib.h>
#define MAX_HOOKS 256
typedef struct vxhook_struct
{
SYMTAB_ID symTblId; /** id of symbol table containing the symbol */
SYMBOL *symbol; /** pointer to symbol entry within symbol table */
void *originalValue; /** original value of symbol */
void *hookedValue; /** hooked value of symbol */
} VXHOOK;
/** counter of installed hooks */
static int hooks = 0;
/** list of installed hooks */
static VXHOOK hook[MAX_HOOKS];
/*
** symbolIterator
** VxWorks callback for symbol table iteration. See symEach(..) for more information.
*/
static BOOL symbolIterator(char *name,
int val,
SYM_TYPE type,
int arg,
UINT16 group)
{
BOOL result = TRUE; /* continue iteration */
char *pName;
pName = (char *)arg;
if ((pName != NULL) && (name != NULL))
{
if (!strcmp(name, pName))
{
result = FALSE; /* symbol found => stop iteration! */
}
}
return (result);
}
/*
** vxHookGet
** Searches the hook list for a specific entry and returns a pointer to it if found.
*/
static VXHOOK *vxHookGet(SYMTAB_ID symTblId, /* symbol table to seachr for name */
char *name, /* name of symbol */
int *index) /* optional return value of index within hook list */
{
VXHOOK *pHook = NULL;
int i;
if (index != NULL)
{
*index = -1;
}
for (i = 0; i < hooks; i++)
{
if ((hook[i].symTblId == symTblId) && (!strcmp(hook[i].symbol->name, name)))
{
pHook = &(hook[i]);
if (index != NULL)
{
*index = i;
}
break;
}
}
return (pHook);
}
/*
** vxHook
** Hooks a symbol within a symbol table (if not already hooked).
*/
STATUS vxHook(SYMTAB_ID symTblId, /* symbol table to seachr for name */
char *name, /* name of symbol */
void *value, /* new value to replace symbol value with */
void **pValue) /* optional pointer receiving original value from symbol table */
{
STATUS result = ERROR;
SYMBOL *symbol;
VXHOOK *pHook;
if ((name != NULL) && (value != NULL))
{
pHook = vxHookGet(symTblId, name, NULL);
if (pHook == NULL) /* symbol not hooked, yet? */
{
if (hooks < MAX_HOOKS) /* free entries available? */
{
pHook = &(hook[hooks]);
symbol = symEach(symTblId, symbolIterator, (int)name);
if (symbol != NULL) /* symbol found? */
{
pHook->symTblId = symTblId;
pHook->symbol = symbol;
pHook->originalValue = symbol->value;
pHook->hookedValue = value;
if (pValue != NULL)
{
*pValue = symbol->value;
}
/* install hook */
symbol->value = value;
printf("Value of symbol '%s' modified from 0x%x to 0x%x.\n", name, pHook->originalValue, pHook->hookedValue);
hooks++;
result = OK;
}
else
{
printf("Symbol '%s' not found in symTblId=0x%08x.\n", name, symTblId);
}
}
else
{
printf("Maximum number of hooks (%d) reached.\n", MAX_HOOKS);
}
}
else
{
printf("Symbol '%s' in symTblId=0x%08x already hooked.\n", name, symTblId);
}
}
return (result);
}
/*
** vxHookList
** Prints a list of all installed hooks to stdout.
*/
STATUS vxHookList(void)
{
int i;
printf(" name symTblId value original\n");
printf("------------------- ---------- ---------- ----------\n");
for (i = 0; i < hooks; i++)
{
printf("%3d: 0x%08x %s\n", i, hook[i].symTblId, hook[i].symbol->name);
}
return (OK);
}
/*
** vxUnhook
** Unhooks a hooked symbol (restoring the original value).
*/
STATUS vxUnhook(SYMTAB_ID symTblId, /* symbol table to search for name */
char *name) /* name of symbol */
{
STATUS result = ERROR;
VXHOOK *pHook;
int i;
pHook = vxHookGet(symTblId, name, &i);
if (pHook != NULL)
{
pHook->symbol->value = pHook->originalValue;
printf("Original value 0x%x of symbol '%s' restored.\n", pHook->originalValue, name);
/* remove hook */
hooks--;
/* shift remaining hooks... */
for (; i < hooks; i++)
{
memcpy(&(hook[i]), &(hook[i + 1]), sizeof(VXHOOK));
}
result = OK;
}
else
{
printf("Hook for '%s' (symTblId=0x%08x) not found.\n", name, symTblId);
}
return (result);
}
To hook wvEvent(..) calls you have to do the following:
#include <wvLib.h>
#include <symLib.h>
STATUS (*WVEVENT_FPTR)(event_t, char *, size_t);
WVEVENT_FPTR orig_wvEvent = wvEvent;
STATUS my_wvEvent(event_t usrEventId, /* event */
char * buffer, /* buffer */
size_t bufSize) /* buffer size */
{
/* create a list of usrEventId... */
return (orig_wvEvent(usrEventId, buffer, bufSize));
}
STATUS hookWvEvents(void)
{
STATUS result = ERROR;
result = vxHook(sysSymTbl, "wvEvent", my_wvEvent, &orig_wvEvent);
return (result);
}
After calling hookWvEvents you can load your application and all calls to wvEvent from within your application will be redirected to my_wvEvent (and then passed on to the original wvEvent function). Remember that hooked symbols stay hooked for your application even if you unhook the symbol using vxUnhook.
Note: This mechanism is also very helpful for application testing and debugging since you can stress your application by forcing system calls to fail...

Logical error in code

Code that I am supposed to fill out which was easy enough.
#define MAX_NAME_LEN 128
typedef struct {
char name[MAX_NAME_LEN];
unsigned long sid;
} Student;
/* return the name of student s */
const char* getName(const Student* s) {
return s->name;
}
/* set the name of student s */
void setName(Student* s, const char* name) {
/* fill me in */
}/* return the SID of student s */
unsigned long getStudentID(const Student* s) {
/* fill me in */
}
/* set the SID of student s */
void setStudentID(Student* s, unsigned long sid) {
/* fill me in */
}
However it says what is the logical error in the following function?
Student* makeDefault(void) {
Student s;
setName(&s, "John");
setStudentID(&s, 12345678);
return &s;
}
I do not see any problems. I tested it. It works fine.
Is it because this should probably be a void function and does not need to be returning anything?
You can't return a pointer to a locally declared variable (Student s). The variable "s" will disappear (become garbage) after the return.
Instead, you need to allocate a student first.
You should probably do this:
void makeDefault(Student* pS) {
setName( pS, "John");
setStudentID( pS, 12345678);
}
And then let the calling application allocate the student.