ตัวเลขที่มีหลักเรียงลำดับ (Sequential Digits Number)
ตัวเลขมีหลักเรียงลำดับก็ต่อเมื่อแต่ละหลักในตัวเลขมีค่ามากกว่าหลักก่อนหน้าทีละ 1
ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ arr ซึ่งมีสมาชิกสองตัวระบุช่วง
ฟังก์ชันควรคืนอาร์เรย์ที่เรียงแล้วของจำนวนเต็มทั้งหมดในช่วง arr (รวมขอบเขต) ที่มีหลักเรียงลำดับ
ตัวอย่างเช่น หากอินพุตคือ
const arr = [1000, 13000];
ผลลัพธ์ควรเป็น
const output = [1234, 2345, 3456, 4567, 5678, 6789, 12345];
ตัวอย่างโค้ด
const arr = [1000, 13000];
const sequentialDigits = ([low, high] = [1, 1]) => {
const findCount = (num) => {
let count = 0;
while(num > 0){
count += 1;
num = Math.floor(num / 10);
}
return count;
};
const helper = (count, start) => {
let res = start;
while(count > 1 && start < 9){
res = res * 10 + start + 1;
start += 1;
count -= 1;
}
if(count > 1){
return 0;
}
return res;
};
const count1 = findCount(low);
const count2 = findCount(high);
const res = [];
for(let i = count1; i <= count2; i++){
for(let start = 1; start <= 8; start++){
const num = helper(i, start);
if(num >= low && num <= high){
res.push(num);
}
}
}
return res;
};
console.log(sequentialDigits(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น
[ 1234, 2345, 3456, 4567, 5678, 6789, 12345 ]