javascript - 如何显示输入的结果及其排列?
问题描述
我需要在最多 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 ] ]
推荐阅读
- excel - 列出文件夹中的文件 excel onedrive
- firebase-authentication - Google / DialogFlow 上的操作:从没有转换对象的 idToken 获取用户数据
- firebase - Firebase 好友列表关系
- jquery - jquery对图像没有响应的爆炸效果
- javascript - 为什么当我通过 fetch API 请求记录我的 React 状态 setState 时会收到两个响应?
- java - 有没有办法使用 Apache Commons Digester 从 xml 中添加 Arraylist 中键的所有值?
- ios - 图像不是从一个 VC 到另一个 VC
- matlab - 如何在 matlab 或 simulink 中对组合(电气和机械)系统执行鲁棒控制
- python - Python 单元测试 - 运行时的模拟补丁?
- aws-lambda - 带有 API Gateway 的 AWS Lambda 返回 500 错误并带有 hello-world 蓝图