Last active
July 11, 2019 02:43
-
-
Save kerrishotts/a0a96dc752e5f93b21a227032c70bf80 to your computer and use it in GitHub Desktop.
Dev.to daily challenge (2019-07-10)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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