我试图写一个函数,它做以下工作:

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

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

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

let permArr = [];
let usedChars = [];

function permute(input) {
    const chars = input.split("");
    for (let i = 0; i < chars.length; i++) {
        const 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
};

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

我真的需要解决方案是在JavaScript。我已经知道如何在python中做到这一点


当前回答

这里有一个很酷的解决方案

Const旋转= ([l,…]Ls], right=[]) => L !== void 0 ?[[l,…ls,……右),…旋转(ls,[…对,l])]: [] Const排列= ([x,…xs]) => X !== 0 ?排列(x) .flatMap ((p) = >旋转(p (x)…… ])) : [[]] console.log(排列(“猫”)

其他回答

为了解决这个问题,我的想法如下…

1- (n)的总排列是(n!)

2-检查组合小n (n <= 4)。

3-应用递归技术。

if(n == 1) // ['a']
    then permutation is (1) ['a']
if(n == 2) // ['a', 'b']
    then permutations are (2) ['a', 'b'] ['b', 'a']
if(n == 3) // ['a', 'b', 'c']
    then permutations are (6) ['a', 'b', 'c'] ['a', 'c', 'b'] ['b', 'a', 'c'] ['b', 'c', 'a'] ['c', 'a', 'b'] ['c', 'b', 'a']

所以…排列行为是有规律的。

和数组实例的总排列是…所有可能的子排列从原始数组中移除每个单个字符,并将该单个字符与它们相对的子排列连接起来。也许代码能更好地解释这一点。

Bye!

function permutations(array) { let permutationList = []; if(array.length == 1) { return array; } for(let i = 0; i < array.length; i++) { let arrayLength1 = [ array[i] ]; let auxArray = Object.values(array); auxArray.splice(i, 1); let subPermutations = this.permutations(auxArray); for(let j = 0; j < subPermutations.length; j++) { let arrayMerge = arrayLength1.concat(subPermutations[j]); permutationList.push(arrayMerge); } } return permutationList; } let results4 = permutations(['a', 'b' ,'c', 'd']); let results6 = permutations(['a', 'b' ,'c', 'd', 'e', 'f']); console.log(results4.length); console.log(results4); console.log(results6.length); console.log(results6);

function nPr(xs, r) {
    if (!r) return [];
    return xs.reduce(function(memo, cur, i) {
        var others  = xs.slice(0,i).concat(xs.slice(i+1)),
            perms   = nPr(others, r-1),
            newElms = !perms.length ? [[cur]] :
                      perms.map(function(perm) { return [cur].concat(perm) });
        return memo.concat(newElms);
    }, []);
}

在精神上类似于@crl的haskell风格的解决方案,但使用reduce:

function permutations( base ) {
  if (base.length == 0) return [[]]
  return permutations( base.slice(1) ).reduce( function(acc,perm) {
    return acc.concat( base.map( function(e,pos) {
      var new_perm = perm.slice()
      new_perm.splice(pos,0,base[0])
      return new_perm
    }))
  },[])    
}
#!/usr/bin/env node
"use strict";

function perm(arr) {
    if(arr.length<2) return [arr];
    var res = [];
    arr.forEach(function(x, i) {
        perm(arr.slice(0,i).concat(arr.slice(i+1))).forEach(function(a) {
            res.push([x].concat(a));
        });
    });
    return res;
}

console.log(perm([1,2,3,4]));

这是一个最小的ES6版本。扁平化和无函数可以从Lodash中提取。

const flatten = xs =>
    xs.reduce((cum, next) => [...cum, ...next], []);

const without = (xs, x) =>
    xs.filter(y => y !== x);

const permutations = xs =>
    flatten(xs.map(x =>
        xs.length < 2
            ? [xs]
            : permutations(without(xs, x)).map(perm => [x, ...perm])
    ));

结果:

permutations([1,2,3])
// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]