How to find the minimum distance between two numbers in an array with C++

1 Answer

0 votes
#include <iostream>
#include <climits>
  
int MinDistance(int arr[], int size, int number1, int number2)
{
    int lastIndex = -1;
    int minDistance = INT_MAX;

    for (int i = 0; i < size; ++i)
    {
        if (arr[i] == number1 || arr[i] == number2) {
            if (lastIndex != -1 && arr[i] != arr[lastIndex]) {
                minDistance = std::min(minDistance, i - lastIndex);
            }

            lastIndex = i;
        }
    }

    return (minDistance == INT_MAX) ? -1 : minDistance;
}
    
int main()
{
    int arr[] = {2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3};
        
    int size = sizeof(arr) / sizeof(arr[0]); 
      
    std:: cout << MinDistance(arr, size, 3, 8);
}

    
/*
run:
    
2
    
*/

 



answered Aug 22, 2022 by avibootz
edited Oct 21 by avibootz
...