Next Bigger Number
const {log} = console;
/*
n(abcde):
ไปฃ่กจไธไธๅๆฏ abcde ๅคง็ๆธๅญ (ไฝ้ๆฏๅช่ฝ็จ abcde ้ๅนพๅๆธๅญ)ใ
f(abcde):
1. ไปฃ่กจๅจ bcde ๅ
งๆพๅบใๆฏ a ๅคง็ๆธๅญๆๅฐ่
ใ๏ผ็ถๅพ่ท a ๅฐ่ชฟ๏ผ
ๅฆๆๆพไธๅฐ๏ผๅฐฑๅๅณ undefinedใ
2. ๅฐ่ชฟๅพ๏ผๅพ้ข็ๆธๅญใๅพๅฐๆๅฐๅคงใ๏ผ่ท็ฌฌไธๅๆธๅญๆฅ่ตทไพ๏ผ็ถๅพๅๅณใ
n(abcde) = abc+f(de) || ab+f(cde) || a+f(bcde) || f(abcde)
*/
// assume: `k` -> string of digits.
// suppose k = abcd, b = next bigger digit than `a`, then:
// f(abcd) = b + smallest(acd)
function f(k) {
// 1. find next bigger digit than leading digit
let arr = k.substring(1).split('').sort(); // sort is key
let i = arr.findIndex(c => +c > +k[0]);
// 2. if not found, return undefined.
if (i === -1) return undefined;
// if found, interchange them.
let b = arr[i]; arr[i] = k[0];
return b + arr.sort().join(''); // remember to sort again
}
// assume: `k` -> string of digits.
// next bigger number
function n(k) {
let next;
let left = k.length - 2;
while (!next && left >= 0) {
let found = f(k.substring(left));
if (found) next = k.substring(0, left) + found;
left -= 1;
}
return next;
}
// -------- log --------
// f(k)
[
3412, // 4123
4312, // undefined
]
.map(n => f(String(n)))
.forEach(x => log(x));
// n(k)
[
3412, // 3421
4312, // 4321
59884848459853, // 59884848483559
]
.map(k => n(String(k)))
.forEach(x => log(x));
const {log} = console;
/*
Next bigger number with the same digits
https://www.codewars.com/kata/55983863da40caa2c900004e
ไธไธๅๆธๅญ๏ผ
next(abcd)
ไธๆฏ๏ผใa ไธ็จๅ๏ผ็ถๅพๅจ bcd ๅ
งๆพไธไธๅๆธๅญใ
a + next(bcd)
ไธ็ถๅฐฑๆฏ๏ผใๅพ bcd ่ชฟไธๅๅๅฅฝๆฏ a ๅคง็ๆธๅญไธไพ๏ผ็ถๅพๅฉไธๆธๅญ็ฑๅฐๅฐๅคงๆใ
b + first(acd) = f(abcd)
ไนๅฐฑๆฏ๏ผ(n ไปฃ่กจ next)
n(a) = undefined (x)
n(ab) = a+n(b) || f(ab)
= x || f(ab)
= f(ab)
โญ๏ธ ๅพๆญคไพ็ฅ้๏ผๆๅๅช่ฆๅฎ็พฉ n(a) = undefined๏ผๅ
ถไป็ๆณ้ฝๆ่ชๅๆจๆผใ
n(abcd)
= a+n(bcd) || f(abcd)
= a+(b+n(cd) || f(bcd)) || f(abcd)
*/
// f(abcd) = b + first(acd)
// where:
// b = next bigger digit than `a`
//
// assume: `k` -> string of digits.
function f(k) {
// 1. find next bigger digit than leading digit
let arr = k.substring(1).split('').sort(); // sort is key
let i = arr.findIndex(c => +c > +k[0]);
// 2. if not found, return undefined.
if (i === -1) return undefined;
// if found, interchange them.
let b = arr[i]; arr[i] = k[0];
return b + arr.sort().join(''); // remember to sort again
}
// assume s is a "String" of digits
// n(abcd) = a + n(bcd) || f(abcd)
function next(s){
// โญ๏ธ base cases:
if (s.length <= 1) return undefined;
// โญ๏ธ recursive case:
let found = next(s.substring(1));
return (found) ? s[0] + found : f(s);
}
// main
function nextBigger(n){
let s = next(String(n))
return s ? +s : -1;
}
// -------- log --------
[
(2017), // 2071
(715801), // 715810
(9999999999), // -1
(70168141041296), // 70168141041629
]
.map(n => nextBigger(n))
.forEach(x => log(x));
codewars โฉ Next Bigger Number
codepen โฉ
next bigger? - ็จใ็ฑๅ ง่ๅคใ็ๆผ็ฎๆณใ(while)
next bigger number? - ็จใ็ฑๅค่ๅ งใ็ๆผ็ฎๆณใ(recursive)
Last updated