javascript - 如何使用递归将元素插入数组中的所有位置?

标签 javascript arrays algorithm recursion

我需要使用递归完成以下任务:

Declare a function insert_all_positions, which takes for arguments: an element, x, and an array, arr. Functions must return an array of arrays, with each array corresponding to arrs with x inserted in a possible position. That is, if arr is the length N, then the result is an array with N + 1 arrays.

例如insert_all_positions(10, [1,2,3])的结果是数组:

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

到目前为止我有这段代码:

function insert_all_positions (x, arr) {
    if (arr.length === 1) {
        return arr.concat(x)
    }
    else {

    }
}

最佳答案

这是一个纯递归。

function f(x, A){
  return A.length ? [[x, ...A]].concat(
    f(x, A.slice(1)).map(e => [A[0]].concat(e))) : [[x]]
}

var x = 10
var A = [1, 2, 3]

console.log(JSON.stringify(f(x, A)))

关于javascript - 如何使用递归将元素插入数组中的所有位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59355770/

相关文章:

javascript - Vue DevTools 正确更新但浏览器窗口不更新

c - 写入文件 C 时忽略\0 个字符

c# - 在字符串中查找关键字和关键短语的算法

c++ - 使用单调堆栈背后的直觉

php - 循环遍历 php 中的表格以找到适合我的数据的最佳位置

javascript - JScript 中的 NodeJS + JQuery php 变量

javascript - 如何在鼠标悬停时创建 javascript/css fadeInDown?

c++ - C++ 中 std::pair 数组的问题?

javascript - 了解 Node 中的回调

php - 递归调用 array_values() 重新索引可变深度菜单数组