dimanche 29 mai 2016

Extremely slow code execution time

For any given combination 'C' as an input of size 'k'. Following code computes the index of all the subsets of 'k-1' when all the combinations are arranged in lexicographic order. Combination 'C' consists of integers in sorted order from [1 to 'n'].

The following code has snippets borrowed from link1 and also the function 'nCr'-[Couldn't post the link as I had misplace. If anyone can point please let me know I will add it]

On executing the code, it seems to be very inefficient and takes unusually long time. Any help to improve it or point out issues is highly appreciated

#include <iostream>
#include <vector>

int nCr(int n, int r) {
    //Compute the factorials
    int ans = 1;
    r = std::min(r, n - r);
    for (int j = 1; j <= r; j++, n--) {
        if (n % j == 0) {
            ans *= n / j; 
        } else if (ans % j == 0) {
            ans = (ans / j) * n;
        } else {
            ans = (ans * n) / j;
            }
        }   
    return ans;
}



std::vector<int> compute_index (int n, int k, std::vector<int>& combination) {

    std::vector<int> result;
    result.clear();

    for (int ll = 0; ll < combination.size(); ++ll) {
        int index = 0;
        int j = 0;
        if (ll == 0) index = 1;
        for (int i = 0; i != k; ++i)
        {
            int test = combination[i];
            if (test == combination[ll]) {
                test = combination[(ll+1)%combination.size()];
            }
            for (++j; j != test; ++j)
            {
                index += nCr(n - j, k - i - 1);
            }
        }

        std::cout << index + 1 << std::endl;
        result.push_back(index);
    }
    return result;
}

int main()
{
    int n = 5;
    int k = 2;

    std::vector<int> combination  = {1, 2, 3};

    auto result = compute_index(n, k, combination);

    return 0;
}

Command to compile it :

g++ -std=c++11 -O3 test.cpp -o test

Aucun commentaire:

Enregistrer un commentaire