19
Jan
2020

Hackerrank Sequence Equation (C++)

C++ :

vector<int> permutationEquation(vector<int> p) {
    vector<int> permuted;
    int indexAtI = -1, x = 1, indexAtJ = -1;

    while(x <= p.size()){
        for(int i = 0; i < p.size(); i++){
            if(x == p[i]){
                indexAtI = i + 1;
                cout << indexAtI << endl;
                for(int j = 0; j < p.size(); j++){
                    if(p[j] == indexAtI){
                        indexAtJ = j + 1;
                        break;
                    }
                }
            }
        }
        x++;
        permuted.push_back(indexAtJ);
    }

    return permuted;
}

Explanation:

Note: This is a terrible, terrible solution. Look at the number of nested loops! Yes, it works, but loopsss!

The question was not easy to understand, so the breakdown is this. Given a vector, find the index of index of a number. For example, given a vector p of 3 digits, [2, 3, 1], assuming p[1] is 2, p[2] is 3, p[3] is 1, get the index of 2, 3 and 1 respectively, which is p[p[2]] = 3, p[p[3]] = 1, and p[p[1]] = 2.

The outermost while loop goes through the inner loops for p.size() times, and x is set to x++ after each round. The middle for loop (looping with i) finds the first index of each x, starting from x = 1, and stores the found number in indexAtI before going into the next for loop (looping with j), to find index j of number indexAtI. This number is then stored in indexAtJ, and after breaking out of the for loop, push it into permuted vector.

A better solution without this many loops would be to find the p((i + 1) + 1). Probably would attempt to do this in another language.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *