jeudi 2 juillet 2015

C++ hash map for fibbonacci

I've recently 'downgraded' (not saying that Java is better) from Java to C/C++. I've become confident in working with pointers and custom data structures.

I've discovered collections available in C++11 like map and unordered_set.

I've implemented the Fibbonaci using dynamic programming but I have a bug and I am not able to find it.

Mentions:

1)I am not sure if I am supposed to pass the map by reference (I've read some posts that say my approach is fine).

2)I am compiling the code with g++ and my version of g++ classifies 'std=c++11' as experimental.

What happens:

If I try to go for only 30 numbers - it works but is incredibly slow.

If I try to go for 50 - it halts. (without printing for 0, 1, 2 - so even if the map was always empty it should at least print the first few...)

Here's the code:

#include <cstdio>
#include <cstdlib>
#include <map>

using namespace std;

long fibb(int k, map<int, long> map);

int main(int argc, char** argv)
{
    int a;
    map<int, long> map;


    for(int i = 0; i < 30; i++)
        printf("%lu ",fibb(i, map));

    printf("\n");
    return 0;
}

long fibb(int k, map<int, long> map)
{
    //printf("we are doing: %d\n", k);
    if(k == 0 || k == 1)
    {
        return 1;
    }
    else
    {
        long a,b;
        if(map.find(k - 1) != map.end())
        {
            auto x = map.find(k-1) -> second;
            a = x;
        }       
        else
        {
            a = fibb(k - 1, map);
        }

        if(map.find(k - 2) != map.end())
        {
            auto x = map.find(k - 2) -> second;
            b = x;
        }
        else
            b = fibb(k - 2, map);

        map[k] = a+b;
        return a + b;
    }
}

Aucun commentaire:

Enregistrer un commentaire