JavaScript algorithm to give every possible combination of items and store them in an array [duplicate]

*爱你&永不变心* 提交于 2019-12-13 02:56:46

问题


I'm looking for a good way to make a program for this problem:

First an array with string values is given:

    var array1 = ["a", "b", "c", "d"]

Next I would like to store every possible combination(order) of the string values in new arrays

ex:

    combo1 = ["a", "b", "d", "c"]
    combo2 = ["a", "c", "b", "d"]
    combo3 = [...etc.]

The program needs to be able to do this with big array's as well. With for example up to 20 items in the first array (array1). So it needs to do all the work of creating the 'combo array's' automatically with a function.

What would be a good way to tackle this problem? Preferably with JavaScript, but I'm open to hear about it in out languages.

As you may have guessed, I am a fairly beginner when it comes to programming. I have got the basics down and am now trying to wright a program for a project. Please help and thank you in advance!


回答1:


In haskell you could use permutations

 permutations "abc" == ["abc","bac","cba","bca","cab","acb"]

In JavaScript you need to write the permutations function yourself:

function permutations(list) {
    if (list.length <= 1)
        return list.slice();

    var result = []
      , i = 0
      , resultRest
      , current
      , rest
      , j;
    for(; i<list.length; i++) {
        rest = list.slice(); // make a copy of list
        current = rest.splice(i, 1);
        permutationsRest = permutations(rest);
        for(j=0; j<permutationsRest.length; j++) {
            result.push(current.concat(permutationsRest[j]));
        }
   }
   return result;
}
permutations(['a', 'b', 'c'])
> [ [ 'a', 'b', 'c' ],
    [ 'a', 'c', 'b' ],
    [ 'b', 'a', 'c' ],
    [ 'b', 'c', 'a' ],
    [ 'c', 'a', 'b' ],
    [ 'c', 'b', 'a' ] ]

However, if your input is big this will take a while. Maybe you should think about another approach.



来源:https://stackoverflow.com/questions/20610175/javascript-algorithm-to-give-every-possible-combination-of-items-and-store-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!