Aug 3, 2009

char str1[]="Hello";//

char str1[]="Hello";//
char *str2=”Hello”;// const
they are different, str1 is on the local stack, str2 is also on the const data segment

static variable

Static variable
Which is destroyed when program terminates
for(int x=0; x<10; x++)
{
for(int y=0; y<10; y++)
{
static int number_of_times = 0;
number_of_times++;
}
}
or
class user
{
private:
int id;
static int next_id;

public:
static int next_user_id()
{
next_id++;
return next_id;
}
/* More stuff for the class user */
user()
{
id = user::next_id++; //or, id = user.next_user_id();
}
};
int user::next_id = 0;

Aug 1, 2009

Given a set of points (x,y) on a 2D coord system, identify list of 2D coords that are of distance less than x units long.

Given a set of points (x,y) on a 2D coord system, identify list of 2D coords that are of distance less than x units long.
Eg.
Let x = 1;
Given (0,0), (0,1), (1, 2), (4,6);
Return 1 -> (0,0), (0,1)
Build the kd tree, iteratively find the neighbors for the node where the distance is less than 1
http://en.wikipedia.org/wiki/Kd-tree#Nearest_neighbor_search
foo(tree* root, tree* node, stack s,int len)
{
if(!root) return;
if(DIS(root,node)<(-1*len))
foo(root->left,node,s,len);
else if(DIS(root,node)>len))
foo(root->right,node,s,len);
else
{ if(!root->left&&!root->right)//left node is the point node
{
s.push(root);
return;
}
foo(root->left,node,s,len);
foo(root->right,node,s,len);
}
}

Jul 31, 2009

There exits 2D array. We need to find out whether a given string ("microsoft") exits in the given matrix. The string can be vertical or horizontal or

There exits 2D array. We need to find out whether a given string ("microsoft") exits in the given matrix. The string can be vertical or horizontal or in snake form but not in diagonal.

mi..
...c.o..oft
.....r.s

the basic way is just scan the 2d array row by row (col by col ) and find the matching, we can use backtrack
{{{
int row;
int col;
int len;
char str[len]="microsoft";
char a[row][col]="…";
foo(int idx, int i,int j, char* str,const& char a[][col])
{
for(;i < row;i++,j=0)
for(;j < col;j++)
{
if(str[idx]==a[i][j])
{
if(idx==len-1) return true;
bool result=foo(idx+1,i,j+1,str,a);
if(result) return true;
}
}
return false;
}
}}}

Jul 28, 2009

A floor of size 8x8 has to be covered by bricks of size 1x2. How many ways are there to layout bricks in the floor? Generalize the problem to the floo

A floor of size 8x8 has to be covered by bricks of size 1x2. How many ways are there to layout bricks in the floor? Generalize the problem to the floor of size MxN and bricks of size PxQ each.

int foo(int n,int x,int y)
{
if(x>=n||y>=n)
return 0;
if(x==n-1&&y==n-1)
return 1;
return foo(n,x+2,y+0)+foo(n,x+1,y+1)+foo(n,x+0,y+1)+foo(n,x+0,y+2)+foo(n,x+1,y+0);
}