เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของจำนวนเต็มเป็นอาร์กิวเมนต์เดียว ฟังก์ชันต้องกำหนดว่าสามารถแบ่งอาร์เรย์เป็นสองซับอาร์เรย์ได้หรือไม่ ที่ผลรวมของสมาชิกในทั้งสองซับอาร์เรย์เท่ากัน โดยต้องใช้สมาชิกทุกตัวในอาร์เรย์เดิม
ตัวอย่าง
ถ้าอาร์เรย์นำเข้าคือ:
const arr = [5, 3, 7, 4, 1, 8, 2, 6];
ผลลัพธ์ควรเป็น:
const output = true;
เพราะซับอาร์เรย์ที่ต้องการคือ [5, 3, 4, 6] และ [7, 1, 8, 2] ทั้งคู่มีผลรวม 18
ตัวอย่างโค้ด
const arr = [5, 3, 7, 4, 1, 8, 2, 6];
const canPartition = (arr = []) => {
const sum = arr.reduce((acc, val) => acc + val);
if (sum % 2 !== 0) {
return false;
}
const target = sum / 2;
const array = new Array(target + 1).fill(false);
array[0] = true;
for (const num of arr) {
if (array[target - num]) {
return true;
}
for (let i = target; i >= num; i--) {
array[i] = array[i - num];
}
}
return false;
};
console.log(canPartition(arr));
ผลลัพธ์
true