JavaScript算法给出项目的所有可能组合并将它们存储在数组中 [英] JavaScript algorithm to give every possible combination of items and store them in an array

查看:81
本文介绍了JavaScript算法给出项目的所有可能组合并将它们存储在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种解决此问题的程序的方法:

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

例如:

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

该程序还必须能够使用大型数组来做到这一点。例如,第一个数组(array1)中最多包含20个项目。因此,它需要完成使用功能自动创建组合数组的所有工作。

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.

什么是解决此问题的好方法?最好使用JavaScript,但我愿意以各种语言来了解它。

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!

推荐答案

在haskell中,您可以使用排列

In haskell you could use permutations

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

在JavaScript中,您需要自己编写置换函数:

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.

这篇关于JavaScript算法给出项目的所有可能组合并将它们存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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