loading...

re: Daily Challenge #12 - Next Larger Number VIEW POST

FULL DISCUSSION
 

Here's mine.

First, a function for permuting the digits (using recursion):

const permute = arr => {
    if (arr.length < 2) {
        return (typeof arr === "string" ? [arr] : arr);
    }

    if (typeof arr === "string") {
        return permute(arr.split("")).map(arr => arr.join(""));
    }

    const result = [];
    for (let i = 0; i < arr.length; i++) {
        const unused = arr.map(i => i);
        const candidate = unused.splice(i, 1);
        const permuteUnused = permute(unused);
        for (let r of permuteUnused) {
            result.push([...candidate, ...Array.isArray(r) ? r : [r]]);
        };
    }
    return result;
}

Next, a sorting function:

const numericalOrder = (a, b) => {
    const nA = Number(a);
    const nB = Number(b);
    return nA < nB ? -1
    : nA > nB ? 1
    : 0;
}

And finally, the function to calculate the next largest number itself, relying on the idea that if we sort in numerical ascending order and filter out all the items less than the requested number, then the first one remaining must be our next largest number.

const nextLargerNumber = n => {
    const digits = n.toString();
    const nextValidNumbers = permute(digits)
        .sort(numericalOrder)
        .filter(a => Number(a) > n);
    if (nextValidNumbers.length < 1) {
        return null;
    }
    return Number(nextValidNumbers[0]);
}

Full code and tests in gist: gist.github.com/kerrishotts/a0a96d...

Code of Conduct Report abuse