using System;
public static class ArrayDistance
{
/// <summary>
/// Finds the minimum distance between two target values in an array.
/// </summary>
/// <param name="numbers">Input array.</param>
/// <param name="target1">First target value.</param>
/// <param name="target2">Second target value.</param>
/// <returns>
/// The minimum distance between the target values,
/// or -1 if no valid pair exists.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown when numbers is null.
/// </exception>
public static int FindMinimumDistance(int[] numbers, int target1, int target2)
{
if (numbers == null) {
throw new ArgumentNullException("numbers");
}
// Special case:
// Find the minimum distance between consecutive
// occurrences of the same value.
if (target1 == target2) {
return FindMinimumDistanceForSameValue(numbers, target1);
}
int lastSeenIndex = -1;
int minimumDistance = int.MaxValue;
for (int i = 0; i < numbers.Length; i++)
{
int currentValue = numbers[i];
// Skip irrelevant values.
if (currentValue != target1 && currentValue != target2) {
continue;
}
/*
* If we previously encountered one of the target
* values and the current value is the other target,
* update the minimum distance.
*/
if (lastSeenIndex >= 0 && currentValue != numbers[lastSeenIndex])
{
int distance = i - lastSeenIndex;
if (distance < minimumDistance) {
minimumDistance = distance;
}
}
// Remember the most recent occurrence.
lastSeenIndex = i;
}
return minimumDistance == int.MaxValue
? -1
: minimumDistance;
}
/// <summary>
/// Finds the minimum distance between consecutive
/// occurrences of the same value.
/// </summary>
private static int FindMinimumDistanceForSameValue(int[] numbers, int target)
{
int previousIndex = -1;
int minimumDistance = int.MaxValue;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] != target) {
continue;
}
if (previousIndex >= 0) {
int distance = i - previousIndex;
if (distance < minimumDistance) {
minimumDistance = distance;
}
}
previousIndex = i;
}
return minimumDistance == int.MaxValue
? -1
: minimumDistance;
}
}
public class Program
{
public static void Main()
{
int[] numbers = {2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3};
int result =
ArrayDistance.FindMinimumDistance(
numbers,
3,
8);
if (result >= 0) {
Console.WriteLine(
"Minimum distance between 3 and 8: {0}",
result);
}
else {
Console.WriteLine("No valid pair found.");
}
}
}
/*
run:
Minimum distance between 3 and 8: 2
*/