gpt4 book ai didi

javascript - 我如何显示输入的结果及其排列?

转载 作者:行者123 更新时间:2023-11-30 14:02:53 25 4
gpt4 key购买 nike

我需要在最多 5 个字符的输入中显示输入值的所有排列

我制作了这个 Codepen 示例,但效果不佳

https://codepen.io/alonsoct00/pen/WBeXEp

我的脚本:

<script>
function permute(a) {
if (a.length < 5) return [a];
var c, d, b = [];
for (c = 0; c < a.length; c++) {
var e = a.splice(c, 1),
f = permute(a);
for (d = 0; d < f.length; d++) b.push([e].concat(f[d]));
a.splice(c, 0, e[0])
}
return b

}

function permuteval() {
var txtval = document.getElementById('permute_this').value;
document.getElementById('results').innerHTML =
(permute([txtval]).join("\n"));

}
</script>

谢谢

最佳答案

尝试使用展开运算符:

document.getElementById('results').innerHTML = (permute([...txtval]).join("\n"));

不确定这是否是您正在寻找的确切输出

https://codepen.io/jfitzsimmons/pen/RmNZGP

此外,我喜欢这段用于排列的代码:

const permutations = arr => {
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
return arr.reduce(
(acc, item, i) =>
acc.concat(
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
),
[]
);
};
EXAMPLES
permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]

https://30secondsofcode.org/

关于javascript - 我如何显示输入的结果及其排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56009997/

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