DEV Community

Discussion on: Daily Challenge #215 - Difference of 2

Collapse
 
aminnairi profile image
Amin

JavaScript

Assuming the input should be an array of unsigned integers.

"use strict";

/**
 * Find the pairs that have a difference of two.
 *
 * @param {number[]} An array of unsigned integers.
 *
 * @throws {Error}      If the function is not called with one argument.
 * @throws {TypeError}  If the first argument is not an array.
 * @throws {TypeError}  If the first argument is not an array of integers.
 * @throws {TypeError}  If the first argument is not an array of unsigned integers.
 *
 * @return {number[][]} An array of array of unsigned integer pairs
 *
 * @example
 * pairDifference([1, 2, 3, 4]);        // [ [ 1, 3 ], [ 2, 4 ] ]
 * pairDifference([4, 1, 2, 3]);        // [ [ 4, 2 ], [ 1, 3 ] ]
 * pairDifference([1, 23, 3, 4, 7]);    // [ [ 1, 3 ] ]
 * pairDifference([4, 3, 1, 5, 6]);     // [ [ 4, 6 ], [ 3, 1 ], [ 3, 5 ] ]
 */
function pairDifference(numbers) {
    if (arguments.length !== 1) {
        throw new Error("expected one argument");
    }

    if (!Array.isArray(numbers)) {
        throw new TypeError("expected first argument to be an array");
    }

    const length = numbers.length;
    const pairs = [];

    for (let first = 0; first < length; first++) {
        const firstNumber = numbers[first];

        if (!Number.isInteger(firstNumber)) {
            throw new TypeError("expected first argument to be an array of integers");
        }

        if (firstNumber < 0) {
            throw new TypeError("expected first argument to be an array of unsigned integers");
        }

        for (let second = first + 1; second < length; second++) {
            const secondNumber = numbers[second];

            if (!Number.isInteger(secondNumber)) {
                throw new TypeError("expected first argument to be an array of integers");
            }

            if (secondNumber < 0) {
                throw new TypeError("expected first argument to be an array of unsigned integers");
            }

            if (Math.abs(firstNumber - secondNumber) === 2) {
                pairs.push(firstNumber, secondNumber);
            }
        }
    }

    return pairs;
}