dasthan

Alamut

Binary Indexed Trees

Given the frequencies of occurrences of a particular data set, our task is to compute the cumulative frequencies of the data set. Naive Solutions take about O(n) time. But Binary Indexed Trees, which are quite commonly used for computing Cumulative Frequencies efficiently, takes about O(log n).

In case you need a comparison of the asymptotic growth of O(n) and O(log n), take a look at the graph here. This would make huge difference if there are many queries asking for cumulative frequencies.

There is quite a lot of information regarding Binary Indexed Trees out there. Here is my implementation of it.

#ifndef BIT_HPP
#define BIT_HPP
#include<vector>
template<class T>
struct BITNode{
    T freq;
    T cuf;
    BITNode(){
        freq = 0;
        cuf = 0;
    }
};
template<class T>
class BIT{
private:
    typedef std::vector<BITNode<T> > VN;
    void _setElem(int idx,T freq,T cuf){
        elems[idx - 1].freq = freq;
        elems[idx - 1].cuf = cuf;
    }

    BITNode<T> _getElem(unsigned int idx){
        return elems[idx - 1];
    }

    void _propUp(int idx, T change){
        if(change == 0){
            return;
        }

        while(idx <= size){
            BITNode<T> old = _getElem(idx);
            _setElem(idx,old.freq,old.cuf + change);
            idx += (idx & -idx);
        }
    }
public:
    VN elems;
    int size;
    BIT(int size = 0){
        elems.resize(size);
        for(int i = 0; i < size; i++){
            elems[i].freq = 0;
            elems[i].cuf = 0;
        }
         this->size = size;
    }

    void calc(int idx, T val){
        T cuf = val;
        int targetIdx = idx - (idx & -idx);
        int i = idx - 1;
        while(i > targetIdx){
            cuf += _getElem(i).cuf;
            i -= (i & -i);
        }
        _setElem(idx,val,cuf);
    }

    void update(int idx, T val){
        if(idx > size){
            for(int i = size; i < idx; i++){
                BITNode<T> tmp;
                elems.push_back(tmp);
            }
            for(int i = size + 1; i < idx + 1; i++){
                calc(i,0);
            }
            size = idx;
        }
        BITNode<T> old = _getElem(idx);
        T change = val - old.freq;
        _setElem(idx,val,old.cuf);
        _propUp(idx,change);
    }
    T sum(int idx){
        T sum = 0;
        while(idx > 0){
            sum += _getElem(idx).cuf;
            idx -= (idx & -idx);
        }
        return sum;
    }

    void display(){
        for(int i = 0; i < size;i++){
            std::cout << i+1 <<": ("<<elems[i].freq<<", "
            <<elems[i].cuf<<"): "<<sum(i+1)<<std::endl;
        }
    }
};

Latest Updates on this code will be available in my github repo.

A very similar data structure is Segment Tree. An elegant implementation of segment tree can be found here. Segment Trees can also be employed for efficient queries for cumulative frequencies. But BIT is much easier to code.

In case you need to know when to use Segment Trees or Binary Indexed Trees, read Quote of Raziman Thottungal Valapu’s answer to Data Structures: How does one decide when to use a Segment Tree or Fenwick Tree? on Quora.

Sweet Love O’ mine

Well, with the sun scorching outside and with no intention to doze off in this sultry afternoon, a persistent thought about my love and how she has conquered me from a long time kept coming to my mind. So, that made me write this blog!

Have you ever wondered how love grows? How it develops? Well, many say that there is no reason or you don’t know how it spurs in you. Here, I’ll describe how my love conquered me.

When I was in 4th~5th grade or so, for the very first time in my life, there were three of these in the second floor of our school with dull ivory color and having a CRT display with no GUI and a mouse. Thats when we were taught BASIC where we had to give the incremental line numbers on our own and make the program spit out some characters on the display. Writing a program that computed square root of a number itself was a big achievement. Another tool which we were taught was Logo where in we had to move the turtle and draw figures. This was very amusing and as others were struggling with lines and angles I was able to fill up the screen with nice figures as like a flower (arcs displaced in with a constant offset in angle), a man (one circle for the head, one oval for the body and sticks for the limbs). Personally, I also took interest in learning Wordstar55 and also read a book of MS-DOS commands with the helper book. I was also able to make small batch files for copying, renaming and deleting files.

Then a change of place. As I was not able to come to my dad’s office, with no computer to play with, had to take a break for some time. Then my new school taught computers but very basics and I did not get the opportunity to use a computer in my spare time. None of my friends had one ! I also learnt vedic mathematics using a helper book and did a 10 digit X 10 digit multiplication. I still remember that my school correspondent asked one of my friends to verify the answer with a “computer”. Barring some 3 digits in the answer, all others were right, to my surprise.

With the pause (a long pause indeed), we bought a computer when I was in 12th grade. I lived in hostel and could not use the computer at home.After my 12th grade, we shifted back to my old place. In the vacation before I joined my Engineering, I went to a C/C++ class in and started to get in love with the computer again. This time I developed a console application to display the calendar of a particular month or highlight the date in the calendar if a date is given as input. Then I also made a C application to compute the amount of interest for my dad. Later I taught him formulae in MS Excel (C was not a prerequisite for MS Excel).

Then came my college days. When I thought I know at least a bit of C/C++, my peers were kings at it. I hardly had a terminal to work on. Still, whenever I came home, I used my computer to write some short programs and learn. In my college days, we made embedded applications in C and loaded the compiled HEX code into the 8051 microcontroller and started to become interested in them. The first major application I did was to sense the presence of an obstruction at different places using RF transmitter. The main principle of detection was with Frequency Division Multiplexing. The second application was with a Passive IR sensor to detect the presence of the  human being in a large hall and to switch on/off the appliances in that particular segment of the hall. The third application was to develop a USB device to control a simulated Aircraft. This was the first attempt with an ARM architecture based microcontroller. That was a pretty interesting project as it involved interfacing through the USB protocol to any computer. THen the fourth one was small again and it involved displaying the temperature of the inside contents in the cooler we made on a 16 x 2 line LCD display. That was also pretty awesome. The final application in my college was to write a high pass filter with Z-transforms and implement in the microcontoller. That helped my friend partly to get rid of the crude bread board and also to get rid of the need to search for high tolerance capacitors.

Despite the interest in programming, I got a job which involves no programming whatsoever and now think how I satisfy my love? Moonlighting!!!

Now, after I got a terminal on my own, I burn my nights’ oil in it. The things I experimented include learning python, C++ STL, writing a thrift server client program to name a few. I also helped my friend develop a small twitter application.

Despite all the odds, I had/have/will have some or other opportunity to write “PROGRAMS”. I think it is a soulful relationship. It is a never ending journey and my love somehow chases me again and again catching up with me. Thats my love.

So, What’s yours?

Migration

A BIG weekend so to say. Having migrated to Ubuntu 11.10, the first impression is that Unity really unifies the search and application shortcut management seamlessly.  I would like to write certain tweaks that I was forced to do.

1. Power regression:

Ubuntu was sucking out all my battery power and the indicator reported my battery would last for just 1 hr 20 mins which was worse than what my battery used to last in Windows. Searching for power management profile in Ubuntu proved futile. So wondered if there are any tweaks to increase my battery life.

Active state power management switch that is to be enabled in bootloader was not enabled. Lets see how to go about it.

Usually the boot loader settings in Ubuntu lies in a file called grub.cfg in /boot/grub but that is not to be edited directly. There is a file in the

/etc/default/grub

which can be edited by executing

sudo gedit /etc/default/grub

 

ERRORS IN GRUB FILE CAN MAKE YOUR COMPUTER FAIL TO BOOT

Search for GRUB_CMDLINE_LINUX_DEFAULT=”quiet splash” and append “pcie_aspm = force” after the splash. The resulting line looks like

GRUB_CMDLINE_LINUX_DEFAULT=”quiet splash pcie_aspm=force”

Then run the following command to add the changes to the grub file in /boot/grub

sudo update-grub

Although this solved the power drain problem, there were no power profiles whatsoever. On searching, I came to know abt the tool called Jupiter. This tool is not available in the default repositories. It is available through ppa.Lets see how to add it to the repositories. Execute the following commands in your terminal.

  • sudo add-apt-repository ppa:webupd8team/jupiter
  • sudo apt-get update

And then run

sudo apt-get install jupiter

This has a lot of power profiles and if you need more control, install cpufrequtils which allows CPU frequency scaling.

Finally. I get around 2 hours of battery backup with 80% charge.

2. Ethernet speed:

I have a static-ip ethernet connection for my internet. It works on a 10 Mbps full duplex protocol. As with most network cards, my network card is also capable of working in multiple speeds. After installing Ubuntu, I noticed that my network was configured automatically to 100 Mbps full duplex connection. And thats a problem! While searching for a way to fix this, I came across a tool called ethtool. Install this by executing the following command in terminal

sudo apt-get install ethtool

After installing, start configuring your network card by executing

ethtool -s interface_name speed your_speed duplex type

You can use this command to try out all the different combinations of the speed, duplex and other configurations(try going through ethtool -h).

The changes that you make through the ethtool are for the current session only to make these changes permanent, you can write down the commands that worked for you in /etc/network/interfaces file by writing pre-up /sbin/ethtool -s eth0 speed 10 duplex full at the end. Reboot is needed for the changes made to the interfaces file to take effect.

Thats all for now, so far I have been using Code::Blocks for C++ development but now came across a new IDE called Qt Creator which is primarily for developing GUI applications using the Qt library. Interestingly, this Qt project is by Nokia. More on it in next post. 🙂

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Post Navigation