创建所有可能组合的算法 [英] Algorithm to create all possible combinations

查看:90
本文介绍了创建所有可能组合的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写备用网格代码,需要将N个一维网格点(以矢量形式编写)组合到所有可能点的数组中.例如,可以将两个向量(a,b)与(c,d,e)混合,得出以下几点:

I'm writing a spares grid code and need to combine N 1-dimensional grid points (written in vector form) into the an array of all possible points. For example one can mix two vectors (a,b) with (c,d,e) giving the following points:

(a,c)(a,d)(a,e) (b,c)(b,d)(b,e)

(a,c) (a,d) (a,e) (b,c) (b,d) (b,e)

Matlab具有一个称为combvec的功能:

Matlab has a function called combvec:

http://www.mathworks.co.uk/help/nnet/ref/combvec.html

我正在用FORTRAN编写此代码,但是找不到底层算法.该代码需要采用N(N> 1)个向量(即2,3 ... N),并且每个向量可以具有不同的长度.有人知道算法吗?

I'm writing this code in FORTRAN however I can't find the underlying algorithm. The code needs to take in N (N>1) vectors (i.e 2,3...N) and each can be a different length. Does anyone know of an algorithm?

推荐答案

我不了解Fortran,但由于您说找不到底层算法,所以我假设您一旦写完就可以自己编写知道算法.实际上,这很容易.伪代码将是这样的(假设没有重复):

I don't know Fortran, but since you say you can't find the underlying algorithm I'm assuming you will be able to write this yourself once you know the algorithm. It's quite easy actually. The pseudocode would be something like this (assuming there are no duplicates):

index = 0   ! or 1
for each element in first vector
    for each element in second vector
        matrix(index,1) = current element of first vector
        matrix(index,2) = current element of second vector
        index = index + 1
    end for
end for

这将为您提供类似于使用combvec的矩阵. 可能有更有效的方法来执行此操作,但是由于我不了解Fortran的详细信息,因此我无法为您提供帮助.在Matlab中,您当然会对此向量化.

This should give you a matrix similar to the one you would get using combvec. There are probably more efficient ways to do this, but as I don't know the details of Fortran I can't help you there unfortunately. In Matlab you would of course vectorize this.

祝你好运=)

这篇关于创建所有可能组合的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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