编程逻辑问题

时间:2010-12-28 14:12:29

标签: math combinations

我需要一个可以给我所有可能的数组组合的函数。

示例:

$source = array('a', 'b', 'c');
$target = thisiswhatisearch($source);

现在$target应该是这样的:

array('a','b','c','ab','ac','cb','abc')

我不需要aabbcc

我也不需要bacaacb ..因为订单对我来说并不重要。

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

Combination的维基百科条目有一个link to C code来执行此操作。

答案 1 :(得分:0)

试图与语言无关,但我想它的C就像:

function combinations(array arr)
{
  combos = array();
  for (int i=1; i<2**arr.size(); i++)
  {
    int x = i;
    int c = 0;
    str = "";
    while(x>0)
      {
        int rem = x % 2;
        if(rem == 1)
          str += arr[c];
        x = x / 2;
        c++;
      }
    combos.add(str);

   }
return combos;
}

答案 2 :(得分:0)

这是一个不可思议的解决方案。它可能不是最快最干净的,但它有点有效。它是用Java编写的,因为我把它打开了:

public class Combination {

public static void main(String[] args) {
    String[] source = {"a","b","c"};
    List<String> result = combineMe(new ArrayList<String>(Arrays.asList(source)));
    for (String string : result) {
        System.out.println(string);
    }
}

public static List<String> combineMe(List<String> source) {
    List<String> result = new ArrayList<String>();
    if (source.size()==0) {
        result.add("");
        return result;
    }else{
        String tmp = source.remove(0);
        source = combineMe(source);
        for (String string : source) {
            result.add(("" + string).trim());
            result.add(tmp + string);
        }
    }
    return result;
}
}

结果列表中的第一个条目是假的,需要在最后删除