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

การสร้าง Permutations เพื่อให้ได้ผลรวมเป้าหมาย ใช้ตัวเลขซ้ำได้ใน JavaScript


ภาพรวม

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ตัวเลขเป็นอาร์กิวเมนต์แรก และตัวเลขเป้าหมายเป็นอาร์กิวเมนต์ที่สอง ฟังก์ชันควรคืนอาร์เรย์ของซับอาร์เรย์ที่ผลรวมเท่ากับเป้าหมาย สามารถใช้ตัวเลขเดิมซ้ำได้

ตัวอย่าง

อินพุต: const arr = [1, 2, 4]; const sum = 4;

เอาต์พุต:

const output = [
  [1, 1, 1, 1],
  [1, 1, 2],
  [2, 2],
  [4]
]

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

const arr = [1, 2, 4];
const sum = 4;

const getCombinations = (arr = [], sum) => {
  const result = [];
  const pushElement = (i, t) => {
    const s = t.reduce((a, b) => a + b, 0);
    if (sum === s) {
      result.push(t);
      return;
    }
    if (s > sum || i === arr.length) {
      return;
    }
    pushElement(i, t.concat([arr[i]]));
    pushElement(i + 1, t);
  };
  pushElement(0, []);
  return result;
};

console.log(getCombinations(arr, sum));

ผลลัพธ์ในคอนโซล

[ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ], [ 4 ] ]