Skip to content

Instantly share code, notes, and snippets.

@kerrishotts

kerrishotts/20190710.js

Last active Jul 11, 2019
Embed
What would you like to do?
Dev.to daily challenge (2019-07-10)
const assert = expr => {
if (!expr) { throw new Error(`assertion failed`); }
};
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;
};
assert(JSON.stringify(permute("1")) === `["1"]`)
assert(JSON.stringify(permute("12")) === `["12","21"]`)
assert(JSON.stringify(permute("123")) === `["123","132","213","231","312","321"]`);
const numericalOrder = (a, b) => {
const nA = Number(a);
const nB = Number(b);
return nA < nB ? -1
: nA > nB ? 1
: 0;
};
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]);
};
assert(nextLargerNumber(1) === null);
assert(nextLargerNumber(12) === 21);
assert(nextLargerNumber(21) === null);
assert(nextLargerNumber(13) === 31);
assert(nextLargerNumber(31) === null);
assert(nextLargerNumber(25) === 52);
assert(nextLargerNumber(513) === 531);
assert(nextLargerNumber(2019) === 2091);
assert(nextLargerNumber(123456789) === 123456798);
assert(nextLargerNumber(987654321) === null)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment