ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีสตริงทวินิยมยาว 3 ตัวคั่นด้วยช่องว่าง ฟังก์ชันควรจัดเรียงตัวเลขในลำดับเพิ่มขึ้น แต่จัดเรียงเฉพาะเลขคู่ และทิ้งเลขคี่ไว้ที่เดิม
ตัวอย่าง
โค้ดตัวอย่างด้านล่าง:
const str = '101 111 100 001 010';
const sortEvenIncreasing = (str = '') => {
const sorter = (a, b) => {
const findInteger = bi => parseInt(bi, 2);
if (findInteger(a) % 2 === 1 || findInteger(b) % 2 === 1) {
return 0;
}
return findInteger(a) - findInteger(b);
};
const res = str
.split(' ')
.sort(sorter)
.join(' ');
return res;
};
console.log(sortEvenIncreasing(str));
ผลลัพธ์
101 111 100 001 010
คำอธิบายเพิ่มเติม
binary: 101(5), 111(7), 100(4), 001(1), 010(2) เลขคู่: 4,2 → เรียงเป็น 2,4 ตำแหน่งเดิม: index 2=100(4), index 4=010(2) หลังเรียง: index 2=010(2), index 4=100(4) ผลลัพธ์ควรเป็น '101 111 010 001 100' แต่โค้ด sort() ไม่เสถียร (unstable) และ return 0 สำหรับ odd ทำให้ลำดับไม่แน่นอน