/    Sign up×
Community /Pin to ProfileBookmark

Using PHP to Find All Possible Combinations of Something

[B]My pool of letters:[/B]
A a B b C c D d E e

[B]What I’ll be doing with them:[/B]
making random two letter sets (e.g. Be)

[B]What am I asking you to help me with?[/B]
I want to see how many possible combinations there are. And I don’t want the same combination counted twice just because it appeared in a different order (e.g. Be and eB I’d want counted just once). Order does not matter. The combination of letters does.

How could I have PHP do this for me? And if it helps my PHP experience is about 5 stars out of 10. So you don’t have to talk to me like a total novice ?

to post a comment
PHP

21 Comments(s)

Copy linkTweet thisAlerts:
@sridhar_423Sep 27.2006 — [URL=http://www.webdeveloper.com/forum/showthread.php?t=119206&page=2&pp=15]like this[/URL]

if so, u dont need all the six combinations tat i made in the innermost loop for getting different combinations.
Copy linkTweet thisAlerts:
@bokehSep 27.2006 — Do you just want to know the number of combinations or do you want those combinations returned?

My guess is you want [URL=http://en.wikipedia.org/wiki/Permutations_and_combinations#Combination_without_repetition]combinations without repetition[/URL], is that correct? I just want to be certain of what you want before posting something.

I don't want the same combination counted twice just because it appeared in a different order[/QUOTE]The order is irrelevant to a combination so two different orders is only one combination even though it is two permutations. Imagine an apple, a pear and an orange in a fruit salad. It doesn't matter how they are arranged the combination would still be the same.
Copy linkTweet thisAlerts:
@sridhar_423Sep 27.2006 — nCr ..
(e.g. Be and eB I'd want counted just once)[/QUOTE]

[code=php]$chars="AaBbCc";

for($i=0;$i<strlen($chars);$i++){
$i_chr = substr($chars,$i,1);

for($j=($i+1);$j<strlen($chars);$j++){
$j_chr = substr($chars,$j,1);
if($j_chr == $i_chr)
continue;
$i=0;
foreach($words as $keys => $vals)
echo $i++.":".$vals."<BR>";
[/code]

if at all repetetions are also to be counted, u need to add the number of characters for which u want to generate the two-lettered sets. i.e. "6" in this case.

(simple bcos, u r trying to generate just 2 lettered sets)
Copy linkTweet thisAlerts:
@evenstar7139authorSep 28.2006 — Do you just want to know the number of combinations or do you want those combinations returned?[/QUOTE]
You know what that would be VERY helpful if you could show me how to have it return all the results too.

My guess is you want [URL=http://en.wikipedia.org/wiki/Permutations_and_combinations#Combination_without_repetition]combinations with repetition[/URL], is that correct? I just want to be certain of what you want before posting something.[/quote]
Looks right.
Copy linkTweet thisAlerts:
@bokehSep 28.2006 — nCr .. [/QUOTE]The trouble with that solution is it's not dynamic, which would be nicer. The following is dynamic and fast. [code=php]<?php

// view the real output
header('Content-Type: text/plain');

// your string
$letters = 'AaBbCcDdEe';

// convert to array
$letters_array = str_2_array($letters);

echo 'The number of two charcter combinations from that string is '.count($result = get_combos($letters_array, 2))."nn";

echo 'The following is the combinations array'."nn";

print_r(array_2d_to_1d($result));

function get_combos($input, $combo_length)
{
$input = array_values($input);
$code = '';
$cnt = count($input);
$ret = array();
$i0 = -1;
for($i=0;$i<$combo_length;++$i)
{
$k = 'i'.($i+1);
$code .= 'for($'.$k.'=$i'.$i.'+1; $'.$k.'< $cnt-'.($combo_length-$i-1).'; ++$'.$k.') ';
}
$code .= '$ret[] = array($input[$i'.implode('], $input[$i',range(1,$combo_length)).']);';
eval($code);
return $ret;
}

function str_2_array($input)
{
for($i = 0, $len = strlen($input); $i < $len; $i++)
{
$rtn[] = $input[$i];
}
return $rtn;
}

function array_2d_to_1d($input)
{
foreach($input as $key => $value)
{
$rtn[$key] = implode($value);
}
return $rtn;
}

?>[/code]
Copy linkTweet thisAlerts:
@sridhar_423Sep 29.2006 — :eek: Excellent ..
Copy linkTweet thisAlerts:
@s_mackSep 29.2006 — Hi there. I found this post using Google and its almost what I need.

I'm a PHP programmer rank 1.5 our of 10 ? But I'm learning.

I want to do the exact same thing, except that instead of just one common pool of data, I want to find all the combinations of sets of data. Like this:

Set 1: a, b, c

Set 2: d, e

Set 3: f, g

And generate the following combinations:

1: a, d, f

2: a, d, g

3: a, e, f

4: a, e, g

5: b, d, f

6: b, d, g

...

11: c, e, f

12: c, e, g

But I get lost because I don't know how many elements are in a set, nor do I know how many sets there are. The only thing I know (for my purpose) is that you can only select one element from each set.

This has implications in eCommerce, for example, for finding possible combinations of options when there are more than one option. Take t-shirts: they can be S, M, L, XL but they can also be Green, Red, or Blue as well as Printed or Blank.

Thanks. I just can't seem to quite wrap my head around it.

  • - Steven
  • Copy linkTweet thisAlerts:
    @bokehSep 29.2006 — I'm a PHP programmer rank 1.5 our of 10 ? But I'm learning.[/QUOTE]Your biggest trouble will be not crashing the server due to the high number of combinations. For example if an item were to have 10 attributes with 10 choices per attribute that is 10 billion combinations. The idea of php with a default RAM setting of 8 megabytes being able to return such an array and without timing out is fairly remote to say the least.
    Copy linkTweet thisAlerts:
    @s_mackSep 29.2006 — Your biggest trouble will be not crashing the server due to the high number of combinations. For example if an item were to have 10 attributes with 10 choices per attribute that is 10 billion combinations. The idea of php with a default RAM setting of 8 megabytes being able to return such an array and without timing out is fairly remote to say the least.[/QUOTE]

    Fair enough, but it doesn't mean its not a problem that can't be solved. I never said there would be a 10x10 grid. I mean, you could have given the same answer to the girl at the top of this thread by saying, "what if you have a sample of every letter of every alphabet in every country..."

    The problem and question are most certainly valid... I just don't know how to code the loops.

    And for most ecommerce applications, the above example I gave is much more typical... you'd have 12 combinations. Much much less than a billion and certainly within the computational capabilities of most servers, I would suspect.

    - Steven
    Copy linkTweet thisAlerts:
    @s_mackSep 29.2006 — I've gathered that I need to loop for each set.
    <i>
    </i>for (var i=0;i&lt;sizeof($dataset1);i++) {
    for (var j=0;j&lt;sizeof($dataset2);j++) {
    for (var k=0;k&lt;sizeof($dataset3);k++) {
    for (var l=0;l&lt;sizeof($dataset4);l++) {
    echo $dataset1[$i] . $dataset2[$j] . $dataset3[$k] . $dataset4[$l];
    }
    }
    }
    }


    The trick that I see is that you don't know how many levels to go in. I'm sure there are plenty of php situations where loops like this are necessary... this is where not knowing php very well hurts ? I know what I need to do (I think)... I just have no idea how to do it.

    Is this the wrong place?

  • - Steven
  • Copy linkTweet thisAlerts:
    @bokehSep 29.2006 — The trick that I see is that you don't know how many levels to go in.[/QUOTE]If you don't know the number of levels the script needs to be dynamic. This means the script would write the code on the fly (based on the input) and then evaluate it. [code=php]<?php

    $datasets[] = array('a','b','c');
    $datasets[] = array('d','e');
    $datasets[] = array('f','g');

    foreach(datasets($datasets) as $data)
    {
    echo $data . "<br>n";
    }

    function datasets($datasets)
    {
    $part1 = '';
    $part2 = '$rtn[] = ';
    $i = 0;
    foreach(array_keys($datasets) as $key)
    {
    $part1 .= 'for($k'.$i.'=0; $k'.$i.'<count($datasets['.$key.']); ++$k'.$i.') ';
    $part2 .= ($i?'.':'') . '$datasets['.$key.'][$k'.$i++.']';
    }
    $part2 .= ';';
    eval($part1.$part2);
    return $rtn;
    }

    ?>[/code]
    Copy linkTweet thisAlerts:
    @evenstar7139authorSep 30.2006 — Hi there. I found this post using Google and its almost what I need.[/QUOTE]
    I'm curious. What did you type in that brought this page up? I always try to give my posts titles that preview what they're about and I wonder if that is what made this come up in your search.
    Copy linkTweet thisAlerts:
    @evenstar7139authorSep 30.2006 — The trouble with that solution is it's not dynamic, which would be nicer. The following is dynamic and fast. [code=php]<?php

    // view the real output
    header('Content-Type: text/plain');

    // your string
    $letters = 'AaBbCcDdEe';

    // convert to array
    $letters_array = str_2_array($letters);

    echo 'The number of two charcter combinations from that string is '.count($result = get_combos($letters_array, 2))."nn";

    echo 'The following is the combinations array'."nn";

    print_r(array_2d_to_1d($result));

    function get_combos($input, $combo_length)
    {
    $input = array_values($input);
    $code = '';
    $cnt = count($input);
    $ret = array();
    $i0 = -1;
    for($i=0;$i<$combo_length;++$i)
    {
    $k = 'i'.($i+1);
    $code .= 'for($'.$k.'=$i'.$i.'+1; $'.$k.'< $cnt-'.($combo_length-$i-1).'; ++$'.$k.') ';
    }
    $code .= '$ret[] = array($input[$i'.implode('], $input[$i',range(1,$combo_length)).']);';
    eval($code);
    return $ret;
    }

    function str_2_array($input)
    {
    for($i = 0, $len = strlen($input); $i < $len; $i++)
    {
    $rtn[] = $input[$i];
    }
    return $rtn;
    }

    function array_2d_to_1d($input)
    {
    foreach($input as $key => $value)
    {
    $rtn[$key] = implode($value);
    }
    return $rtn;
    }

    ?>[/code]
    [/QUOTE]


    There's a problem with this. I made this the pool: 12345

    And it gave me this: The number of two charcter combinations from that string is 10 The following is the combinations array Array ( [0] => 12 [1] => 13 [2] => 14 [3] => 15 [4] => 23 [5] => 24 [6] => 25 [7] => 34 [8] => 35 [9] => 45 )

    Where's 11 22 33 44 and 55?
    Copy linkTweet thisAlerts:
    @bokehSep 30.2006 — I always try to give my posts titles that preview what they're about and I wonder if that is what made this come up in your search.[/QUOTE]It's more likely the search engine realised the quality of the answer rather than the quality of the question.
    Copy linkTweet thisAlerts:
    @bokehSep 30.2006 — There's a problem with this. I made this the pool: 12345

    And it gave me this: The number of two charcter combinations from that string is 10 The following is the combinations array Array ( [0] => 12 [1] => 13 [2] => 14 [3] => 15 [4] => 23 [5] => 24 [6] => 25 [7] => 34 [8] => 35 [9] => 45 )

    Where's 11 22 33 44 and 55?[/QUOTE]
    Let's say I gave you 1 apple, 1 banana, 1 orange, 1 pear, and 1 peach. 2 apples would not be a possible combination, would it? Unless you had a magic wand.

    My guess is you want [URL=http://en.wikipedia.org/wiki/Permutations_and_combinations#Combination_without_repetition]combinations without repetition[/URL], is that correct? I just want to be certain of what you want before posting something.[/QUOTE]I specifically asked this question in the first place before posting any code.
    Copy linkTweet thisAlerts:
    @evenstar7139authorSep 30.2006 — When I said without repetition I meant not counting the same combination twice if it simply comes up in a different order, e.g. BA and AB.

    Perhaps all I need to do is make each letter in the pool double? e.g. instead of ABCDEFG have AABBCCDDEEFFGG.....if this was ran through your same script, would it work like I wanted?

    **Edit: Tried this idea and it didn't work XD Now I'm totally dependant on your reply.
    Copy linkTweet thisAlerts:
    @bokehSep 30.2006 — I meant not counting the same combination twice if it simply comes up in a different order, e.g. BA and AB.[/QUOTE]That is why I provided the link, so you could understand the difference between [I]with [/I]and [I]without[/I] and the difference between [I]permutation [/I]and [I]combination[/I]. Anyway your suggestion won't work but the following will:[code=php]<?php

    $source = 'AaBbCcDdEe';

    foreach(combos_with_repetition($source, 2) as $combo)
    {
    echo "$combo<br>n";
    }

    function combos_with_repetition($input, $combo_len = 2)
    {
    for($i = 0; $i < $combo_len; ++$i)
    {
    @$part1 .= 'for($k'.$i.' = 0, $len = strlen($input); $k'.$i.' < $len; ++$k'.$i.') ';
    @$part2 .= ($i?'.':'') . '$input[$k'.$i.']';
    }
    eval($part1.'$rtn[] = '.$part2.';');
    return $rtn;
    }

    ?>[/code]
    Copy linkTweet thisAlerts:
    @evenstar7139authorSep 30.2006 — That is why I provided the link, so you could understand the difference between with and without and the difference between permutation and combination.[/Quote]
    I did and I thought I did understand.

    Oh and uhh as I progressed in planning for this genetics program I want to write my pool has changed.

    It's going to have 14 different sets but each set will only have one gene in it.

    Example:

    A
    ------


    A1

    A2

    A3

    A4

    A5

    For the purpose of this I'll say which one from the A set is chosen is random. It could be A1, A2, A4, who knows.

    Now I have 13 more sets like this....here's B

    B
    --------


    B1

    B2

    And then there's

    C
    ----------


    C1

    C2

    C4

    C4

    C5

    and there are 12 more sets after this. What I want to illustrate is they do not have the same number of things in each set. They can have as few as 2 or as many as 6.

    Now, that's not the hard part. I need to know how many combinations all of these sets can make when put together with one random thing from each set. Here are several examples to help you grasp what I am saying:

    A3

    B1

    C4
    ---------


    A1

    B2

    C3
    ----------


    A4

    B1

    C5
    ---------


    A1

    B2

    C2

    Do you understand what it is I need to do? Feel free to ask anything you need to know, like if you need to see what's in the rest of the sets. I just didn't want to make you feel like I'm making you write the whole program for me. I imagine it will be pretty lengthy so I don't want to make you do that. But if you could figure out what it is I need to do and tell me I'll gladly write the code myself.

    Now, that's not all. I want to insert all of these possible combinations into a database. I'd want all the genes imploded, in alphabetical order, into a single string like this: A1B2C2 and it could be inserted as simply as INSERT INTO table (gene_combo, color) VALUES ('$imploded_string', '') | Don't worry about the value of color as I'll come back later and fill that in. Heh this whole script is an easier way for me to write down what color each genetic combo makes! I calculate there are 288,000 combinations in all but hey I have a staff of slaves, erm, admin XD
    Copy linkTweet thisAlerts:
    @bokehSep 30.2006 — I'm sure you are on a wind up. Every time a piece of code has been posted you change the goal posts. And you haven't bothered to say thank you once. Good luck with the code, but I've got no intention of writing anything else for you.
    Copy linkTweet thisAlerts:
    @evenstar7139authorSep 30.2006 — I'm sorry you feel that way. I guess I was wrong when I thought the people here were kind. I'll have to go somewhere else where the people will help me.

    Edit: Oh yeah. When I was over at devshed I used to say thank you to almost everybody....until I realized most of them didn't care. Some of them would even stomp me for my kindness. I vividly remember one or two guys getting pissed off at me because I said they were too cool to be geeks and they took it as an insult.

    So...yah...thanks a lot. For making me uncomfortable for posting here now 'cause I know you're around and pry gonna post mean things on my threads. *sigh* onto another forum I move. Where people actually care for one another...
    Copy linkTweet thisAlerts:
    @bokehOct 01.2006 — I know you're around and pry gonna post mean things on my threads.[/QUOTE]When someone doesn't say thank you for help and refers to others human beings as their slaves it doesn't inspire me to help them.
    ×

    Success!

    Help @evenstar7139 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.6,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...