-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-10.js
32 lines (26 loc) · 965 Bytes
/
day-10.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// https://dev.to/thepracticaldev/daily-challenge-12-next-larger-number-3f3o
// @author Mohamed Elidrissi
const test = require('./test');
function nextLargerNumber(n) {
if (n < 0) return -1;
const digits = n.toString().split('');
let possibleCombinations = [];
for (let i = 0; i < digits.length; i++) {
for (let j = 0; j < digits.length; j++) {
const combination = Array.from(digits);
const first = combination.splice(i, 1).join('');
const second = combination.splice(j, 1).join('');
combination.splice(i, 0, second);
combination.splice(j, 0, first);
possibleCombinations.push(parseInt(combination.join('')));
}
}
possibleCombinations = possibleCombinations.filter(v => v > n);
return possibleCombinations.length > 0
? Math.min(...possibleCombinations)
: -1;
}
test(21, nextLargerNumber(12));
test(2091, nextLargerNumber(2019));
test(-1, nextLargerNumber(5));
test(-1, nextLargerNumber(-16));