Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

จัดเรียงสมาชิกอาร์เรย์ใหม่ใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลข arr เป็นอาร์กิวเมนต์เดียว

อาร์เรย์ arr จะมีความยาวเป็นเลขคู่เสมอ

ฟังก์ชันควรคืนค่า true ก็ต่อเมื่อสามารถจัดเรียงใหม่ได้ ที่ทำให้ arr[2 * i + 1] = 2 * arr[2 * i] สำหรับทุก 0 <= i < length(arr) / 2

ตัวอย่างเช่น หากอินพุตคือ

const arr = [4, -2, 2, -4];

ผลลัพธ์ควรเป็น

const output = true;

คำอธิบายผลลัพธ์

เราสามารถจับคู่ได้สองกลุ่ม [-2,-4] และ [2,4] เพื่อสร้าง [-2,-4,2,4] หรือ [2,4,-2,-4]

ตัวอย่างโค้ด

const arr = [4, -2, 2, -4]; 
const canRearrange = (arr = []) => {
  const map = arr.reduce((acc, num) => {
    acc[num] = (acc[num] || 0) + 1;
    return acc;
  }, {});
  const keys = Object.keys(map)
    .map(key => Number(key))
    .sort((a, b) => a - b);
  for (const key of keys) {
    if (key < 0) {
      while (map[key] > 0) {
        if (map[key / 2] > 0) {
          map[key] -= 1;
          map[key / 2] -= 1;
        } else {
          return false;
        }
      }
    } else {
      while (map[key] > 0) {
        if (map[key * 2] > 0) {
          map[key] -= 1;
          map[key * 2] -= 1;
        } else {
          return false;
        }
      }
    }
  }
  return true;
};
console.log(canRearrange(arr));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น

true