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 .
Monday, December 17, 2007
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){
....
}
}
Sunday, October 21, 2007
Lazy Initailization Idioms
Double check idiom is supposedly the best lazy initialization technique
private static Foo foo = null;
public static void getFoo(){
if (null == foo){
synchronized (Foo.class){
if ( null == foo){
foo = new Foo();
}
}
}
return foo;
}
This is the double check idiom , it works great with primitives but is flawed when it
comes to object references cause the behaviour of object references after synchronized is
undefined.
Solution 1:
private static Foo foo = new Foo();
public static void getFoo(){
return foo;
}
Solution 2:
private static Foo foo = null;
public synchronized Foo getFoo(){
if (null == Foo)
foo = new Foo();
return foo;
}
Solution 3:
Initialize on demand - holder class Idiom
private static class Holder{
static Foo foo = new Foo();
}
public static Foo getFoo(){
return Holder.foo;
}
private static Foo foo = null;
public static void getFoo(){
if (null == foo){
synchronized (Foo.class){
if ( null == foo){
foo = new Foo();
}
}
}
return foo;
}
This is the double check idiom , it works great with primitives but is flawed when it
comes to object references cause the behaviour of object references after synchronized is
undefined.
Solution 1:
private static Foo foo = new Foo();
public static void getFoo(){
return foo;
}
Solution 2:
private static Foo foo = null;
public synchronized Foo getFoo(){
if (null == Foo)
foo = new Foo();
return foo;
}
Solution 3:
Initialize on demand - holder class Idiom
private static class Holder{
static Foo foo = new Foo();
}
public static Foo getFoo(){
return Holder.foo;
}
set_new_handler in
The correct way of overriding the new operator can be something. Here i try to highlight how one can go about doing so .
typedef void (*new_handler)();
In the new header file , a typedef new handler is defined . This typedef basically refers to
the function that the new operator will call if it is not able to allocate memory properly.
Generally the new operator specification looks for the new_handler to allocate more or release
memory so that the new operator can call it properly.
new_handler set_new_handler(new_handler handler);
is a function also found in that installs the new handler . A typical implementation
of this should return the old_handler that was replaced.
The new operator throws std::bad_alloc exception when it is not able to allocate memory.
Class specific handlers can be installed for class specific new operator .
The code for managing the operator and the handler can go in one templatised base class.
Derived classes can then inherit from this class . The base class is very specialized class
as it only provides only one type of functionality.Such type of classes are called mixins.
template
class NewHandler{
public:
static new_handler set_new_handler(new_handler handler);
static void* operator new(size_t size);
private:
static new_handler currentHandler;
};
template
new_handler NewHandler::currentHandler;
template
new_handler NewHandler::set_new_handler(new_handler handler){
new_handler oldHandler = currentHandler;
currentHandler = handler;
return oldHandler;
}
template
void* NewHandler::operator new(size_t size){
new_handler globalHandler = std::set_new_handler(NewHandler::currentHandler):
void * memory;
try{
// try to allocate memory using global new operator
memory = ::operator new(size);
}catch(std::bad_alloc &){
std::set_new_handler(globalHandler);
// propogate all the exceptions
throw;
}
// reinstall the saved gloabal handler
std::set_new_handler(globalHandler);
return memory;
}
Now any class X can use NewHandler like this :
class X : public NewHandler {
};
typedef void (*new_handler)();
In the new header file , a typedef new handler is defined . This typedef basically refers to
the function that the new operator will call if it is not able to allocate memory properly.
Generally the new operator specification looks for the new_handler to allocate more or release
memory so that the new operator can call it properly.
new_handler set_new_handler(new_handler handler);
is a function also found in
of this should return the old_handler that was replaced.
The new operator throws std::bad_alloc exception when it is not able to allocate memory.
Class specific handlers can be installed for class specific new operator .
The code for managing the operator and the handler can go in one templatised base class.
Derived classes can then inherit from this class . The base class is very specialized class
as it only provides only one type of functionality.Such type of classes are called mixins.
template
class NewHandler{
public:
static new_handler set_new_handler(new_handler handler);
static void* operator new(size_t size);
private:
static new_handler currentHandler;
};
template
new_handler NewHandler
template
new_handler NewHandler
new_handler oldHandler = currentHandler;
currentHandler = handler;
return oldHandler;
}
template
void* NewHandler
new_handler globalHandler = std::set_new_handler(NewHandler
void * memory;
try{
// try to allocate memory using global new operator
memory = ::operator new(size);
}catch(std::bad_alloc &){
std::set_new_handler(globalHandler);
// propogate all the exceptions
throw;
}
// reinstall the saved gloabal handler
std::set_new_handler(globalHandler);
return memory;
}
Now any class X can use NewHandler like this :
class X : public NewHandler
};
Thursday, October 18, 2007
Finalizer guardian Idiom
Finalizer Guardian idiom is nothing but an anonymous class assigned to a private final instance variable within a class that wants to override the finalize method .
The anonymous class takes the responsibility of calling the finalize method of the enclosing class.
All this in code looks like :
public class A{
private final Object b = new Object(){
protected void finalize() throws Throwable {
// finalize the outer A here
}
};
}
The anonymous class takes the responsibility of calling the finalize method of the enclosing class.
All this in code looks like :
public class A{
private final Object b = new Object(){
protected void finalize() throws Throwable {
// finalize the outer A here
}
};
}
Little Sugar (Handling Exceptions in Finalize )
Lets consider a scenario where you have a class A and a subclass of that class called B.
Now say you override the finalize method in class B then you need to explicitly invoke the
finalize method of the parent.
So your implementation should look like this :
protected void finalize() throws Throwable {
try{
}finally{
super.finalize();
}
}
That way , any exceptions thrown in the finalize method would not cause the finalize method to terminate and leave the object in a corrupt state.
Now say you override the finalize method in class B then you need to explicitly invoke the
finalize method of the parent.
So your implementation should look like this :
protected void finalize() throws Throwable {
try{
}finally{
super.finalize();
}
}
That way , any exceptions thrown in the finalize method would not cause the finalize method to terminate and leave the object in a corrupt state.
Little Sugar (Java Finalization )
Uncaught exceptions thrown in the finalize method of an object are not caught . Infact they cause the finalization process to terminate and leave the object in a corrupt state . Now that's weird ...
So the best of the rule of thumb would be to avoid finalizers. Instead explicit termination methods should be called that can be invoked in the finally block .
So the best of the rule of thumb would be to avoid finalizers. Instead explicit termination methods should be called that can be invoked in the finally block .
Monday, October 08, 2007
Contributing to the Eclipse Cool Bar
To add stuff to the eclipse cool bar , u need to
1) implement the extension point org.eclipse.ui.editor .
2) Specify a contributorClass for the above mentioned extension point.
This contributor class will provide actions that would be contributed to the
coolbar.
Lets call this calls MyContributorClass.
3) Have this class extend BaseEditorContributor , It should override contributeToParentCoolbar .
4) In the given method create a ContributionItem that would be contributed to the coolbar.
Lets call this myContributionItem.
5) Use the parentCoolBarManager to add create a ToolBarManager.
IToolBarManager toolbar = new ToolBarManager(parentCoolBarManager.getStyle())
6) Add myContributionItem to toolbar.
toolbar.add(myContributionItem);
7) Create a ToolBarContributionItem and add it to the parent cool bar.
ToolBarContributionItem toolBarItem = new ToolBarContributionItem(toolbar,myContributionItem.getId())
parentCoolBarManager.add(toolBarItem);
and finally
coolBarItems.add(toolBarItem);
parentCoolBarManager and coolBarItem are protected members and are available from the base class .
1) implement the extension point org.eclipse.ui.editor .
2) Specify a contributorClass for the above mentioned extension point.
This contributor class will provide actions that would be contributed to the
coolbar.
Lets call this calls MyContributorClass.
3) Have this class extend BaseEditorContributor , It should override contributeToParentCoolbar .
4) In the given method create a ContributionItem that would be contributed to the coolbar.
Lets call this myContributionItem.
5) Use the parentCoolBarManager to add create a ToolBarManager.
IToolBarManager toolbar = new ToolBarManager(parentCoolBarManager.getStyle())
6) Add myContributionItem to toolbar.
toolbar.add(myContributionItem);
7) Create a ToolBarContributionItem and add it to the parent cool bar.
ToolBarContributionItem toolBarItem = new ToolBarContributionItem(toolbar,myContributionItem.getId())
parentCoolBarManager.add(toolBarItem);
and finally
coolBarItems.add(toolBarItem);
parentCoolBarManager and coolBarItem are protected members and are available from the base class .
Sunday, September 23, 2007
what is e raised to i * Pi
The other day i was seeing some presentation . During the presentation i came across a mathematical puzzle . The puzzle asked about what is the value of
value = e ^ (i * Pi) ??
now this would have been really really easy if i was in 12 th grade . But Since its a been long time since 12 th grade and few yrs since by B.S degree . It took some thinking ..
So the solution is :
well if you remember complex numbers then then you can say
e ^ (i * x ) = cos (x) + i sin(x)
so e ^ ( i * Pi ) = cos (Pi) + i sin (Pi)
since cos (pi) = -1
sin (pi ) = 0
e ^ (i * pi) = -1
Duh .. so much for my memory :( ..
value = e ^ (i * Pi) ??
now this would have been really really easy if i was in 12 th grade . But Since its a been long time since 12 th grade and few yrs since by B.S degree . It took some thinking ..
So the solution is :
well if you remember complex numbers then then you can say
e ^ (i * x ) = cos (x) + i sin(x)
so e ^ ( i * Pi ) = cos (Pi) + i sin (Pi)
since cos (pi) = -1
sin (pi ) = 0
e ^ (i * pi) = -1
Duh .. so much for my memory :( ..
Tuesday, August 21, 2007
Showing an Eclipse View Programatically
In eclipse non savable containers are called views . It pretty easy to create a view , all you need to do is to implement an extension - point (org.eclipse.ui.views) and add features to a class . If you want to implement your own view , you can google it you 'll find a number of articles about it .
In this blog entry i tell you how to show/hide an existing view programatically .
Scenario1 : Assuming you have created a view whose view ID is "my.view" and you want to show this view .
Scenario2: You know the view id of some view and you want to show that view programatically.
IWorkbench workbench = PLatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
workbenchWindow.getActivePage().showView("my.view");
// to hide a view
workbenchWindow.getActivePage().hideView("my.view");
PlatformUI is a plugin that can give information about currently active windows and objects in an eclipse session . Its available to us so we use it to get the current workbench window . In eclipse workbench window is the main window . Each window has one or more pages . We get the active page . In the active page we either show or hide the view we are interested in .
In this blog entry i tell you how to show/hide an existing view programatically .
Scenario1 : Assuming you have created a view whose view ID is "my.view" and you want to show this view .
Scenario2: You know the view id of some view and you want to show that view programatically.
IWorkbench workbench = PLatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
workbenchWindow.getActivePage().showView("my.view");
// to hide a view
workbenchWindow.getActivePage().hideView("my.view");
PlatformUI is a plugin that can give information about currently active windows and objects in an eclipse session . Its available to us so we use it to get the current workbench window . In eclipse workbench window is the main window . Each window has one or more pages . We get the active page . In the active page we either show or hide the view we are interested in .
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)