Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,624 questions

56,911 answers

573 users

How to find the minimum distance between two numbers in an array with Node.js

1 Answer

0 votes
"use strict";

/**
 * Finds the minimum distance between two values in an array.
 *
 * Example:
 * numbers = [2, 1, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3];
 * target1 = 3
 * target2 = 8
 *
 * Result: 2
 *
 * @param {number[]} numbers - Array to search.
 * @param {number} target1 - First target value.
 * @param {number} target2 - Second target value.
 * @returns {number}
 * Returns the minimum distance between the targets,
 * or -1 if no valid pair exists.
 * @throws {TypeError} If numbers is not an array.
 */
function findMinimumDistance(numbers, target1, target2) {
    if (!Array.isArray(numbers)) {
        throw new TypeError("numbers must be an array.");
    }

    // Special case: both targets are the same value.
    if (target1 === target2) {
        return findMinimumDistanceBetweenDuplicates(
            numbers,
            target1
        );
    }

    let lastSeenIndex = -1;
    let minimumDistance = Number.MAX_SAFE_INTEGER;

    for (let currentIndex = 0; currentIndex < numbers.length; currentIndex++) {
        const currentValue = numbers[currentIndex];

        // Ignore values that are not one of the targets.
        if (currentValue !== target1 && currentValue !== target2) {
            continue;
        }

        /*
         * If we've previously seen one target value and
         * the current value is the other target value,
         * update the minimum distance.
         */
        if (
            lastSeenIndex >= 0 &&
            currentValue !== numbers[lastSeenIndex]
        ) {
            const distance =
                currentIndex - lastSeenIndex;

            minimumDistance = Math.min(
                minimumDistance,
                distance
            );
        }

        // Store the most recent occurrence.
        lastSeenIndex = currentIndex;
    }

    return minimumDistance === Number.MAX_SAFE_INTEGER
        ? -1
        : minimumDistance;
}

/**
 * Finds the minimum distance between consecutive
 * occurrences of the same value.
 *
 * @param {number[]} numbers - Array to search.
 * @param {number} target - Value to search for.
 * @returns {number}
 * Returns the minimum distance between occurrences,
 * or -1 if fewer than two occurrences exist.
 */
function findMinimumDistanceBetweenDuplicates(
    numbers,
    target
) {
    let previousIndex = -1;
    let minimumDistance = Number.MAX_SAFE_INTEGER;

    for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] !== target) {
            continue;
        }

        if (previousIndex >= 0) {
            const distance = i - previousIndex;

            minimumDistance = Math.min(
                minimumDistance,
                distance
            );
        }

        previousIndex = i;
    }

    return minimumDistance === Number.MAX_SAFE_INTEGER
        ? -1
        : minimumDistance;
}

/*
 * Example usage
 */
const numbers = [2, 1, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3];

const result = findMinimumDistance(numbers, 3, 8);

console.log(
    result >= 0
        ? `Minimum distance between 3 and 8: ${result}`
        : "No valid pair found."
);


/*
run:

Minimum distance between 3 and 8: 2

*/

 



answered Aug 25, 2022 by avibootz
edited 13 hours ago by avibootz

Related questions

...