首页 > 解决方案 > 如何显示输入的结果及其排列?

问题描述

我需要在最多 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>

谢谢

标签: javascriptarraysinputpermutation

解决方案


尝试使用扩展运算符:

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/


推荐阅读