JavaScript 中的排列? [英] Permutations in JavaScript?

查看:23
本文介绍了JavaScript 中的排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个执行以下操作的函数:

I'm trying to write a function that does the following:

  • 将一个整数数组作为参数(例如 [1,2,3,4])
  • 创建一个包含 [1,2,3,4] 的所有可能排列的数组,每个排列的长度为 4

下面的函数(我在网上找到的)通过将字符串作为参数并返回该字符串的所有排列来实现这一点

the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string

我不知道如何修改它以使其适用于整数数组,(我认为这与某些方法在字符串上的工作方式与在整数上的工作方式不同有关,但我不确定...)

I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...)

var permArr = [], usedChars = [];
function permute(input) {
  var i, ch, chars = input.split("");
  for (i = 0; i < chars.length; i++) {
    ch = chars.splice(i, 1);
    usedChars.push(ch);
    if (chars.length == 0)
      permArr[permArr.length] = usedChars.join("");
    permute(chars.join(""));
    chars.splice(i, 0, ch);
    usedChars.pop();
  }
  return permArr
};

注意:我希望函数返回整数数组,不是字符串数组.

Note: I'm looking to make the function return arrays of integers, not an array of strings.

我真的需要 JavaScript 的解决方案.我已经想出了如何在 python 中做到这一点

I really need the solution to be in JavaScript. I've already figured out how to do this in python

推荐答案

有点晚了,但想在这里添加一个稍微优雅的版本.可以是任何数组...

Little late, but like to add a slightly more elegant version here. Can be any array...

function permutator(inputArr) {
  var results = [];

  function permute(arr, memo) {
    var cur, memo = memo || [];

    for (var i = 0; i < arr.length; i++) {
      cur = arr.splice(i, 1);
      if (arr.length === 0) {
        results.push(memo.concat(cur));
      }
      permute(arr.slice(), memo.concat(cur));
      arr.splice(i, 0, cur[0]);
    }

    return results;
  }

  return permute(inputArr);
}

添加 ES6 (2015) 版本.也不会改变原始输入数组.在 Chrome 的控制台中工作...

Adding an ES6 (2015) version. Also does not mutate the original input array. Works in the console in Chrome...

const permutator = (inputArr) => {
  let result = [];

  const permute = (arr, m = []) => {
    if (arr.length === 0) {
      result.push(m)
    } else {
      for (let i = 0; i < arr.length; i++) {
        let curr = arr.slice();
        let next = curr.splice(i, 1);
        permute(curr.slice(), m.concat(next))
     }
   }
 }

 permute(inputArr)

 return result;
}

所以...

permutator(['c','a','t']);

收益...

[ [ 'c', 'a', 't' ],
  [ 'c', 't', 'a' ],
  [ 'a', 'c', 't' ],
  [ 'a', 't', 'c' ],
  [ 't', 'c', 'a' ],
  [ 't', 'a', 'c' ] ]

还有……

permutator([1,2,3]);

收益...

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

这篇关于JavaScript 中的排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆