How to find the minimum distance between two numbers in a vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <limits>
#include <cstdlib>  // std::abs

/**
 * Finds the minimum distance between two target values in an vector.
 *
 * @param vec Input vector.
 * @param x First target value.
 * @param y Second target value.
 * @return Minimum distance between x and y.
 *         Returns -1 if either value does not exist or no valid pair is found.
 */
int findMinDistance(const std::vector<int>& vec, int x, int y)
{
    int lastSeenIndex = -1;
    int minDistance = std::numeric_limits<int>::max();

    for (int i = 0; i < static_cast<int>(vec.size()); ++i)
    {
        // Check if current element matches either target value
        if (vec[i] == x || vec[i] == y)
        {
            // If we've already seen one of the target values
            if (lastSeenIndex != -1 &&
                vec[i] != vec[lastSeenIndex])
            {
                minDistance = std::min(
                    minDistance,
                    std::abs(i - lastSeenIndex)
                );
            }

            // Update latest occurrence
            lastSeenIndex = i;
        }
    }

    return (minDistance == std::numeric_limits<int>::max())
               ? -1
               : minDistance;
}

int main()
{
    std::vector<int> vec = {2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3};

    int result = findMinDistance(vec, 3, 8);

    if (result != -1) {
        std::cout << "Minimum distance: " << result << '\n';
    }
    else {
        std::cout << "No valid pair found.\n";
    }
}


/*
run:

Minimum distance: 2

*/

 



answered Oct 21 by avibootz
...