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

แทรกสมาชิกเข้าไปทุกตำแหน่งในอาร์เรย์ด้วย Recursion - JavaScript

เราต้องเขียนฟังก์ชัน insertAllPositions ที่รับ 2 อาร์กิวเมนต์: สมาชิก x และอาร์เรย์ arr ฟังก์ชันต้องคืนค่าอาร์เรย์ของอาร์เรย์ โดยแต่ละอาร์เรย์คือ arr ที่แทรก x เข้าไปในตำแหน่งที่เป็นไปได้ทุกตำแหน่ง

ถ้า arr ยาว N ผลลัพธ์จะเป็นอาร์เรย์ที่มี N+1 อาร์เรย์

ตัวอย่าง insertAllPositions(10, [1,2,3]) ควรได้:

const output = [
  [10,1,2,3],
  [1,10,2,3],
  [1,2,10,3],
  [1,2,3,10]
];

ต้องเขียนด้วย recursion เท่านั้น

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

const arr = [1, 2, 3];
const num = 10;

const insertAllPositions = (num, arr) => {
  return arr.length ?
  [[num, ...arr]]
  .concat(insertAllPositions(num, arr.slice(1))
  .map(el => {
    return [arr[0]].concat(el);
  })) :
  [[num]]
};

console.log(insertAllPositions(num, arr));

ผลลัพธ์

จะแสดงผลในคอนโซลดังนี้:

[ [ 10, 1, 2, 3 ], [ 1, 10, 2, 3 ], [ 1, 2, 10, 3 ], [ 1, 2, 3, 10 ] ]