หมายเลขลำดับหลัก
ตัวเลขจะมีตัวเลขเรียงกันก็ต่อเมื่อแต่ละหลักในตัวเลขนั้นมากกว่าตัวเลขก่อนหน้าหนึ่งหลักหนึ่งตัว
ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน 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 ]