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

查看:102
本文介绍了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

推荐答案

如果您注意到,代码实际上将字符拆分为数组在进行任何排列之前,所以你只需删除连接和拆分操作

If you notice, the code actually splits the chars into an array prior to do any permutation, so you simply remove the join and split operation

var permArr = [],
  usedChars = [];

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


document.write(JSON.stringify(permute([5, 3, 7, 1])));

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

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