我需要使用递归完成以下任务:
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/