0

I need a function that can give me all possible combinations of a array back.

Example:

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

Now the $target should look like:

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

I dont need the aa, bb, cc.

I also dont need the the ba, ca, acb.. because the order isn't important to me.

Thanks for any help.

4
  • 4
    What do you have so far? Commented Dec 28, 2010 at 14:14
  • en.wikipedia.org/wiki/Permutations Commented Dec 28, 2010 at 14:21
  • I found this as a part of the solution: stackoverflow.com/questions/1861966/… Commented Dec 28, 2010 at 14:47
  • On the bottom of that page is a solution which uses a pear package. I´ll take that one (-: - thanks for the wikipedia link - Permutation was a good word to search for Commented Dec 28, 2010 at 14:52

3 Answers 3

0

Tried to be language agnostic but i guess its C like:

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

The Wikipedia entry for Combination has a link to C code that does this.

Comments

0

That's an out of the mind solution. It is probably not the fastest and cleanest one, but it kind of works. It's in Java, because I had it open:

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;
}
}

The first entry in the resulting list is a fake one, and needs to be removed at the end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.