09
Jan
2020

Hackerrank Between Two Sets (C++)

C++ :

int getTotalX(vector<int> a, vector<int> b) {
    int numbersCount = 0, aMax = 0, bMin = b[0], divisor = 0, multiplier = 2, originalDivisor = 0;
    bool divisorFound = false;

    //getting largest number in a
    for(int i = 0; i < a.size(); i++){
        if(a[i] > aMax){
            aMax = a[i];
        }  
    }

    //getting smallest number in b
    for(int i = 0; i < b.size(); i++){
        if(b[i] < bMin){
           bMin = b[i];
        }
    }

    divisor = aMax;

    while(!divisorFound){
        for(int i = 0; i < a.size(); i++){
            if(divisor % a[i] != 0){
                divisor = aMax * multiplier;
                if(divisor > bMin){
                    numbersCount = 0;
                    break;
                }
                i = 0;
                multiplier++;
            }
        }
        divisorFound = true;
    }

    originalDivisor = divisor;
    multiplier = 2;

    if(divisor <= bMin){
        while(divisor <= bMin){
            for(int i = 0; i < b.size(); i++){
                if(b[i] % divisor != 0){
                    numbersCount--;
                    break;
                }
            }
            numbersCount++;
            divisor = originalDivisor * multiplier;
            multiplier++;
        }
    }
    return numbersCount;
}

Explanation:

Ok, this one is a nice little challenge on divisors and factors. First, find the largest number in vector a and smallest number in vector b. Next, set the (temporary) divisor for vector a to be aMax.

Now to find the divisor for vector a. This while loops works while divisorFound is not true. However, if at any time while finding the divisor it becomes bigger than the smallest number in vector b (bMin), break out of the loop and set numberCount to 0.

Next step happens if we found the divisor and the ‘found’ divisor is smaller than bMin. originalDivisor is set to the original value of the ‘found’ divisor. Now to check if divisor is a factor of elements in vector b.

In this second while loop, which only works while divisor is smaller or equal to bMin, if divisor is a factor of all the elements in b, numberCount increases by one. However, if divisor is not a factor of any of the elements in b, reduce numberCount by 1 (since numberCount increases for each time the while loop runs) and breaks out of the current inner for loop. Get the next divisor to be tested as a factor for elements in b by multiplying originalDivisor by multiplier, which increases in each loop.

To be honest this is a little ugly and over-complicated. If you have a better solution, we would love to see it.

You may also like...

Leave a Reply

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