Just imagine if your class does not have a default constructor and infact has one that accepts a parameter . In that case few things might not be possible . To illustrate
class Piece{
public:
Piece(int n);
};
Things like these will not work
Piece pieces[10];
Why?? -> cause u don t have a default constructor and trying to create an array of 10 piece instances just tries to call exactly that for every one of them .
Piece * pieces = new Piece[10];
wont work.
How to get it working :
Piece pieces[] = {
Piece(1),
Piece(2),
Piece(3)
};
Another way to get it working would be :
Piece * pieces[10];
: here you are just declaring an array of 10 Piece pointers;
Or Piece* *pieces = new Piece*[10];
But you still need to initialize all the pointers like this :
for(int i = 0;i < 10;i++){ pieces[i] = new Piece(i); }
Another way of initializing accomplishing this would be :
void * memory = operator new[](10 * sizeof(Piece));
this will create memory for 10 piece objects . Now we can go an and make the memory more specific to Piece :
Piece * pieces = static_cast<piece*>(memory);
Now that pieces points to memory for Piece , lets initialize the pieces with code like
for(int i = 0;i < 10;i++){ new(&pieces[i]) Pieces(i); }
Though this arcane technique will get the job done . It seriously is arcane . Not only that it also has the disadvantage of boilerplate code like this :
for(int i = 9;i >= 0;i--){
pieces[i].~Piece();
}
operator delete[] memory;
If we do not follow the 1st approach , we see that what problems we can face . A small hack to get around this problem would be :
class Piece{
public:
Piece(int n = Piece::UNDEFINED);
private:
static const int UNDEFINED;
};
const int Piece::UNDEFINED = -1;
Tuesday, January 15, 2008
Hello Windows Facts
windows.h is the mother of all other header files in windows . It includes other header files .
Windef.h => basic type defintions
winnt.h => type definitions for unicode support.
winbase.h => kernel functions.
winusr.h => user interface functions
wingdi.h => graphics device interface functions.
WINAPI => is a naming convention like __stdcall .
Windef.h => basic type defintions
winnt.h => type definitions for unicode support.
winbase.h => kernel functions.
winusr.h => user interface functions
wingdi.h => graphics device interface functions.
WINAPI => is a naming convention like __stdcall .
Moving Patterns
If you have a layer of objects and each object in that layer shares a certain set of methods . Those methods can be moved in a common super type . This super type that is common for a whole layer is called a layer super type .
Remote Facade is a facade for objects that are not part of a given process address space , in other words whenever you need to access objects that line in other processes you should use a remote facade to encapsulate and operate on remote objects via the facade . The facade make a number of operation invisible and may also cache the most commonly use objects.
When ever data has to marshaled across processes boundaries and lot of data needs to sent . A Data Transfer Object can be used . The parameters are packed into a simple POJO called a DTO and marshaled . On the server side , the server used some sort of assembler to break the DTO and set the corresponding properties on domain objects.
Remote Facade is a facade for objects that are not part of a given process address space , in other words whenever you need to access objects that line in other processes you should use a remote facade to encapsulate and operate on remote objects via the facade . The facade make a number of operation invisible and may also cache the most commonly use objects.
When ever data has to marshaled across processes boundaries and lot of data needs to sent . A Data Transfer Object can be used . The parameters are packed into a simple POJO called a DTO and marshaled . On the server side , the server used some sort of assembler to break the DTO and set the corresponding properties on domain objects.
Friday, January 11, 2008
Floating in a Tree
If you have a priority queue setup of many nodes. Lets say we want to bring the node with the highest value to the top . IN orther words if i have given a heap than how do i modify the heap so that the biggest element is always present at the root.
One simple logic can be . Given a root node of a subtree .
void maxHeapify(int * a,int rootIndex, int heapLength){
int largest = rootIndex;
int leftIndex = left(rootIndex);
int rightIndex = right(rootIndex);
if(leftIndex < heapLength && a[rootIndex] < a[leftIndex]){
largest = leftIndex;
}
if(rightIndex < heapLength && a[largest] < a[rightIndex]){
largest = rightIndex;
}
if(largest != rootIndex){
swap(a[largest],a[rootIndex]);
maxHeapify(a,largest,heapLength);
}
}
The worst case time for floating a node to any another node depending on your optimization would be approximately equal to the height of the tree , which would generally result in something like ~ lg(N) . To give a counter example for a max Heap operating in a heap . lets give a value of 0 to the root , and let all the other nodes be 1 . In that case the program would go all the way down the heap till the last leaf .
One simple logic can be . Given a root node of a subtree .
- Assume the root node is the largest node .
- Now compare the value of root node with left child and mark the one with the bigger value as biggest
- Then compare biggest with the right child now and make the bigger of the two as the new biggest.
- now repeat the above mentioned steps with the new largest node
void maxHeapify(int * a,int rootIndex, int heapLength){
int largest = rootIndex;
int leftIndex = left(rootIndex);
int rightIndex = right(rootIndex);
if(leftIndex < heapLength && a[rootIndex] < a[leftIndex]){
largest = leftIndex;
}
if(rightIndex < heapLength && a[largest] < a[rightIndex]){
largest = rightIndex;
}
if(largest != rootIndex){
swap(a[largest],a[rootIndex]);
maxHeapify(a,largest,heapLength);
}
}
The worst case time for floating a node to any another node depending on your optimization would be approximately equal to the height of the tree , which would generally result in something like ~ lg(N) . To give a counter example for a max Heap operating in a heap . lets give a value of 0 to the root , and let all the other nodes be 1 . In that case the program would go all the way down the heap till the last leaf .
Thursday, January 10, 2008
casts in C++
C++ provides us with 4 types of casting mechanisms . Namely:
In C casting is done via () operator
int i = 7;
e.g double d = (double) i;
in c++ to do something like this one should use static_cast .
e.g double d = static_cast<double>(i);
const_cast
const_cast is used to remove constness of an object .
jump(Person * person);
Person p;
const Person& constPerson = p;
then some thing like this wont work.
jump(&constPerson) , cause jump expects a non const object . To fix this you would have to use something like this.
jump(const_cast<person*>(&constPerson));
dynamic_cast
This cast is used with inheritance hierarchies . Say to cast a between pointers or references of base classes to references or pointers of derived classes.
e.g
Mammal * mammal;
jump(dynamic_cast<person*>(mammal));
if there was a function like
jump(Person& person); then
we would have something like
jump(dynamic_cast<person&>(*mammal));
if the casting is not possible , the dynamic_cast mechaism throws an excetion or the result is null (This is implementation specific)
- static_cast
- const_cast
- dynamic_cast
- reinterpret_cast
In C casting is done via () operator
int i = 7;
e.g double d = (double) i;
in c++ to do something like this one should use static_cast .
e.g double d = static_cast<double>(i);
const_cast
const_cast is used to remove constness of an object .
jump(Person * person);
Person p;
const Person& constPerson = p;
then some thing like this wont work.
jump(&constPerson) , cause jump expects a non const object . To fix this you would have to use something like this.
jump(const_cast<person*>(&constPerson));
dynamic_cast
This cast is used with inheritance hierarchies . Say to cast a between pointers or references of base classes to references or pointers of derived classes.
e.g
Mammal * mammal;
jump(dynamic_cast<person*>(mammal));
if there was a function like
jump(Person& person); then
we would have something like
jump(dynamic_cast<person&>(*mammal));
if the casting is not possible , the dynamic_cast mechaism throws an excetion or the result is null (This is implementation specific)
Wednesday, January 09, 2008
Little Sugar: C++ references
C++ references are a variant of const pointers that always point to something .
Now consider
string s1("abc");
string s2("def");
string & refTos1 = s1;
Now refTosi points to s1.
Even after refTos1 = s2. Its still points to s1 . But the value of s1 is now changed from "abc" to "def"
Now consider
string s1("abc");
string s2("def");
string & refTos1 = s1;
Now refTosi points to s1.
Even after refTos1 = s2. Its still points to s1 . But the value of s1 is now changed from "abc" to "def"
Tuesday, January 08, 2008
Little Sugar : Big Oh
Consider a scenario where you had a list of N numbers . Now say you have an algorithm that finds the does some sort of comparison . If comparison strategy used compares every element with all the succeeding elements . Then on an average the number of comparisons possible in different cases would be something like this :
(n) + (n-1) + (n-2) .... 1
for the 1 st case we have n comparisons
for the 1 st element we have n-1 comparisons
for the 2 nd element we have n-2 comparison .. and so on.
the sum is = ((n)*(n+1))/2 = O(n^2)
(n) + (n-1) + (n-2) .... 1
for the 1 st case we have n comparisons
for the 1 st element we have n-1 comparisons
for the 2 nd element we have n-2 comparison .. and so on.
the sum is = ((n)*(n+1))/2 = O(n^2)
Saturday, December 29, 2007
Java + meta programming framework == EMF
Meta programming is a popular buzz word these days . There is a framework for java , called EMF (Eclipse Modeling Framework ) that tries to add that support to java . The framework makes meta programming look like total crap . It overly complicates stuff to such a large extent that you just feel like just removing it from your project code.
So in short meta-programming in EMF + java = night mare :(
But on the other hand if you are building your domain layer . EMF is a pretty decent choice . It has in build support for a notification mechanism that allows you to listen to various model changes . So your GUI can become lightly couple to the domain layer and can become very responsive .
If other people have tried EMF , i would love to hear their experiences.
So in short meta-programming in EMF + java = night mare :(
But on the other hand if you are building your domain layer . EMF is a pretty decent choice . It has in build support for a notification mechanism that allows you to listen to various model changes . So your GUI can become lightly couple to the domain layer and can become very responsive .
If other people have tried EMF , i would love to hear their experiences.
Monday, December 17, 2007
Little Sugar : Sequences
Given a sequence , the sum of elements from the i th position to the j th position can be easily found by adding the elements from the i th location to the j th location . A better optimization over this is generally to do a cumulative sum of all the elements upto the j th element . Then the
sum of any sub sequence can be found by taking the starting i th location and the ending j th location and subtracting the result of the element at the i th place from the element at the j th place .
sum of any sub sequence can be found by taking the starting i th location and the ending j th location and subtracting the result of the element at the i th place from the element at the j th place .
Saturday, December 15, 2007
All About Heap Sort -- Part 1
HeapSort is a sorting algorithm . It performs in place sorting . Its complexity it O(n lg n).
It makes use of a data structure called heap. The heap data structure is like an array which looks like a complete binary tree.If you imagine the heap array as a tree then each node in the tree will have left and right children . Each of the nodes in the tree map on to elements in the array . Every parent at index (i) will have a left child at index (2 * i ) and a right child at index (2 *i +1 ) in the array . Nodes in the heap follow the heap property . Heaps can be a max heap or a min heap.
In a max heap every Parent will have a higher value than any of its children . Its the opposite in the case of min heap. For the heap sort algorithm a max heap is used , generally a min heap is used for a priority queue.
Since a heap of (n) elements is like a complete binary tree its height is (lg n ) and all basic operations run in a time proportional to the height of the tree . Heap is a complete binary tree filled with elements at all levels except the last one . So the max number of elements in a heap of height (h) is (pow(2,h+1) - 1) . The minimum number of elements is equal to the number of elements in a heap of height (h-1) + 1 element. We add the extra one element because in the actual heap there would be at least one element on the last row containing leaves.
So the minimum number of elements = (pow(2,h) -1 ) + 1
The height of a heap is actually = floor(lg n ) . Since , a heap with height h will have elements (n) = pow(2,h) <= n <= pow(2,h+1)-1 < pow(2,h-1) and hence
h <= lg n < 1 =""> height = floor ( lg n )
It makes use of a data structure called heap. The heap data structure is like an array which looks like a complete binary tree.If you imagine the heap array as a tree then each node in the tree will have left and right children . Each of the nodes in the tree map on to elements in the array . Every parent at index (i) will have a left child at index (2 * i ) and a right child at index (2 *i +1 ) in the array . Nodes in the heap follow the heap property . Heaps can be a max heap or a min heap.
In a max heap every Parent will have a higher value than any of its children . Its the opposite in the case of min heap. For the heap sort algorithm a max heap is used , generally a min heap is used for a priority queue.
Since a heap of (n) elements is like a complete binary tree its height is (lg n ) and all basic operations run in a time proportional to the height of the tree . Heap is a complete binary tree filled with elements at all levels except the last one . So the max number of elements in a heap of height (h) is (pow(2,h+1) - 1) . The minimum number of elements is equal to the number of elements in a heap of height (h-1) + 1 element. We add the extra one element because in the actual heap there would be at least one element on the last row containing leaves.
So the minimum number of elements = (pow(2,h) -1 ) + 1
The height of a heap is actually = floor(lg n ) . Since , a heap with height h will have elements (n) = pow(2,h) <= n <= pow(2,h+1)-1 < pow(2,h-1) and hence
h <= lg n < 1 =""> height = floor ( lg n )
Tuesday, December 04, 2007
Monday, November 26, 2007
What would happen if locks in Java were non re-entrant
Locks in java are re-entrant , that aids locking to work effectively with Object Oriented Programming . Why ??
Just consider , if you have a base class
class Mybase{
public synchronized doStuff(){
}
}
Now If you have a child class extending the base class then,
public class MyChild extends MyBase{
public synchronized doStuff(){
super.doStuff();
}
}
This would cause a deadlock . Why ??
When on the child doStuff is called a lock on the MyBase object is obtained . Now in MyChild::doStuff when super.doStuff() is called the code would again try to get a new lock on
Mybase and if locks were non re-entrant then the thread would block and hence would cause a deadlock.
Just consider , if you have a base class
class Mybase{
public synchronized doStuff(){
}
}
Now If you have a child class extending the base class then,
public class MyChild extends MyBase{
public synchronized doStuff(){
super.doStuff();
}
}
This would cause a deadlock . Why ??
When on the child doStuff is called a lock on the MyBase object is obtained . Now in MyChild::doStuff when super.doStuff() is called the code would again try to get a new lock on
Mybase and if locks were non re-entrant then the thread would block and hence would cause a deadlock.
Thursday, November 22, 2007
Little Sugar : Showing an Eclipse view
You can use an IWorkbenchPage.showView(viewId) to programatically show a view .
To access the current active page you can use the following code
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage = workbenchWindow.getActivePage();
To access the current active page you can use the following code
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage = workbenchWindow.getActivePage();
Little Sugar : Eclipse Views live in pages
In eclipse we have a workbench window in which different types of pages exist .
thats is WorkbenchWindow > Pages
> ActivePage
a workbench window also contains the currently active page .
Each page is a IWorkbenchPage. A WorkbenchPage contains many views .
Each view is a IViewPart.
So Views live in pages and pages live in workbench window
thats is WorkbenchWindow > Pages
> ActivePage
a workbench window also contains the currently active page .
Each page is a IWorkbenchPage. A WorkbenchPage contains many views .
Each view is a IViewPart.
So Views live in pages and pages live in workbench window
Wednesday, November 21, 2007
Little Sugar : Why constantness helps
Say u have a method like this :
const Rational operator*(const Rational& lhs,
const Rational& rhs);
Now consider this (a * b ) = c
If the above method returned a non const object then the above mentioned
assignment would make sense , ideally it should not as it would be violating the
api contract for built ins.
Tuesday, November 20, 2007
Little Sugar : Pointers to Member Functions
Pointers to member functions is a feature that not many people use but its good to know .
So lets have a look at it . Lets assume you have a class
class Person ;
typedef void (Person::*PPMF)();
class Person{
public :
static PPMF blahFunction(){
return &(Person::processAddress);
}
private :
Address address;
void processAddress();
};
Here blah function returns a pointer to the member function processAddress .
Now you have the pointer to the member address , even if it private ( its evil to to access private member function like this) you can invoke this member function now on an instance of a person
class.
Person boo;
eg. PPMF pmf = boo.blahFunction();
invoke the member function like this :
(boo.*pmf)();
So lets have a look at it . Lets assume you have a class
class Person ;
typedef void (Person::*PPMF)();
class Person{
public :
static PPMF blahFunction(){
return &(Person::processAddress);
}
private :
Address address;
void processAddress();
};
Here blah function returns a pointer to the member function processAddress .
Now you have the pointer to the member address , even if it private ( its evil to to access private member function like this) you can invoke this member function now on an instance of a person
class.
Person boo;
eg. PPMF pmf = boo.blahFunction();
invoke the member function like this :
(boo.*pmf)();
Tuesday, November 13, 2007
Little Sugar : Casting away constant ness
In C++ if you create a constant object , say
const String A("Hello World");
String& B = const_cast(A);
can be used to create a non constant reference to the so called constant object and hence
manipulate it .
const String A("Hello World");
String& B = const_cast
can be used to create a non constant reference to the so called constant object and hence
manipulate it .
Monday, November 12, 2007
Little Sugar :const function pointers and references
The syntax in c++ for constant function pointers is like this
Handle& (*const getHandle) = handle;
where handle is a function returning a reference to the handle.
The syntax for reference function pointers is like this:
Handle& (&getHandle) = handle;
Handle& (*const getHandle) = handle;
where handle is a function returning a reference to the handle.
The syntax for reference function pointers is like this:
Handle& (&getHandle) = handle;
Thursday, November 01, 2007
Little Sugar : What does virtual in C++ mean
In c++ if a function is declared virtual for any class, then that class has an associated
virtual table . With each of those virtual functions a special type of virtual table pointer is associated , which has an entry in the virtual table associated with the corresponding class.
These virtual pointers are used at runtime to figure out which virtual function to invoke at runtime.
Making virtual functions inline does not make sense ?? why ...
Inline functions are meant to be made inline , so that means they don't have an explicit address but then if it does not have an address and its virtual then how will it have an entry in the virtual table ??
It will have an entry , cause our friend compiler will generate a function body for us and embed the address somewhere for it .
virtual table . With each of those virtual functions a special type of virtual table pointer is associated , which has an entry in the virtual table associated with the corresponding class.
These virtual pointers are used at runtime to figure out which virtual function to invoke at runtime.
Making virtual functions inline does not make sense ?? why ...
Inline functions are meant to be made inline , so that means they don't have an explicit address but then if it does not have an address and its virtual then how will it have an entry in the virtual table ??
It will have an entry , cause our friend compiler will generate a function body for us and embed the address somewhere for it .
Tuesday, October 30, 2007
Private lock Object Idiom
The private lock object idiom is generally used in making a class Thread Safe.
Instead of using the instance of the object as a lock object an internal private object is used
as a lock object.
private Object lock = new Object();
so the method need to acquire a lock should use the lock object instead of this object.
e.g.
public void foo(){
synchronized(lock){
....
}
}
Instead of using the instance of the object as a lock object an internal private object is used
as a lock object.
private Object lock = new Object();
so the method need to acquire a lock should use the lock object instead of this object.
e.g.
public void foo(){
synchronized(lock){
....
}
}
Subscribe to:
Posts (Atom)
Labels
. linux
(1)
algorithm
(15)
analytics
(1)
bash
(2)
bigoh
(1)
bruteforce
(1)
c#
(1)
c++
(40)
collections
(1)
commands
(2)
const
(1)
cosine similarity
(1)
creating projects
(1)
daemon
(1)
device_drivers
(1)
eclipse
(6)
eclipse-plugin-development
(9)
equals
(1)
formatting
(1)
freebsd
(1)
game programming
(1)
hashcode
(1)
heap
(1)
heaps
(1)
immutable-objects
(1)
java
(19)
JDT
(1)
kernel
(1)
linux
(4)
little sugar
(23)
logging
(1)
machine learning
(1)
marker-resolution
(1)
markers
(1)
mergesort
(1)
mixins
(1)
numbers
(1)
opengl
(2)
patterns
(2)
priority-queue
(1)
programming
(51)
ps
(1)
ranking
(1)
refactoring
(3)
references
(1)
security
(1)
set
(1)
shell
(1)
similarity
(1)
statistics
(1)
stl
(1)
tetris
(1)
threads
(1)
trees
(2)
unicode
(1)
unix
(2)
views
(2)
windows programming
(2)
XNA
(1)