gpt4 book ai didi

javascript - 更好地理解查找字符串排列的解决方案 - javascript

转载 作者:行者123 更新时间:2023-11-29 10:28:08 25 4
gpt4 key购买 nike

我试图更好地理解递归和函数式编程,我认为一个很好的实践示例是使用递归和现代方法(如 reduce、filter 和 map)创建字符串的排列。

我找到了这段漂亮的代码

const flatten = xs =>
xs.reduce((cum, next) => [...cum, ...next], []);

const without = (xs, x) =>
xs.filter(y => y !== x);

const permutations = xs =>
flatten(xs.map(x =>
xs.length < 2
? [xs]
: permutations(without(xs, x)).map(perm => [x, ...perm])
));

permutations([1,2,3])
// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

来自 Permutations in JavaScript?作者:马顿萨里

我对它进行了一些分隔,以便添加一些控制台日志来调试它并了解它在幕后做了什么

const flatten = xs => {
console.log(`input for flatten(${xs})`);
return xs.reduce((cum, next) => {
let res = [...cum, ...next];
console.log(`output from flatten(): ${res}`);
return res;
}, []);
}

const without = (xs, x) => {
console.log(`input for without(${xs},${x})`)
let res = xs.filter(y => y !== x);
console.log(`output from without: ${res}`);
return res;
}

const permutations = xs => {
console.log(`input for permutations(${xs})`);
let res = flatten(xs.map(x => {
if (xs.length < 2) {
return [xs]
} else {
return permutations(without(xs, x)).map(perm => [x, ...perm])
}
}));
console.log(`output for permutations: ${res}`)
return res;
}

permutations([1,2,3])

我想我对每个方法的作用有足够的了解,但我似乎无法概念化它们是如何组合在一起创建 [[1, 2, 3], [1, 3, 2] , [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

谁能一步一步地告诉我引擎盖下发生了什么?

最佳答案

为了获得所有排列,我们执行以下操作:

我们从左到右取数组的一个元素。

 xs.map(x => // 1

对于所有其他元素,我们递归地生成排列:

 permutations(without(xs, x)) // [[2, 3], [3, 2]]

对于每个排列,我们添加我们在开始时取出的值:

 .map(perm => [xs, ...perm]) // [[1, 2, 3], [1, 3, 2]]

现在对所有数组元素重复,结果是:

 [
// 1
[[1, 2, 3], [1, 3, 2]],
// 2
[[2, 1, 3], [2, 3, 1]],
// 3
[[3, 1, 2], [3, 2, 1]]
]

现在我们只需要flatten(...) 那个数组就可以得到想要的结果。

整个事情可以表示为递归调用树:

 [1, 2, 3]
- [2, 3] ->
- [3] -> [1, 2, 3]
- [2] -> [1, 3, 2]
- [1, 3] ->
- [1] -> [2, 3, 1]
- [3] -> [2, 1, 3]
- [1, 2] ->
- [1] -> [3, 2, 1]
- [2] -> [3, 1, 2]

关于javascript - 更好地理解查找字符串排列的解决方案 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53306200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com