B11002
B11002

Reputation: 91

PHP array collect

I have alphabet array 24 character: "A B C D E F G H I J K L M N O P Q R S T U V W X"

I want collect all case with: 3 unique characters.

First case: ABC, DEF, GHI, JKL, MNO, PQR, STU, VWX

Upvotes: 0

Views: 15547

Answers (3)

Brian
Brian

Reputation: 541

This is a little late coming, but for anyone else reading over this: If you are looking to split a string into 3-character chunks, try PHP's built in str_split() function. It takes in a $string and $split_length argument. For example:

$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWX';
$grouped  = str_split($alphabet, 3);

var_export( $grouped );

This outputs the following array:

array ( 0 => 'ABC', 1 => 'DEF', 2 => 'GHI', 
        3 => 'JKL', 4 => 'MNO', 5 => 'PQR', 
        6 => 'STU', 7 => 'VWX', )

This works for the example given in the question. If you want to have every possible combination of those 24 letters, Artefacto's answer makes more sense.

Upvotes: 2

NikiC
NikiC

Reputation: 101946

$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$c = strlen($alphabet);
$result = array();

for ($i = 0; $i < $c; ++$i) {
    $current0 = $i;
    for ($j = 0; $j < $c; ++$j) {
        if ($current0 == $j) continue;
        $current1 = $j;
        for ($k = 0; $k < $c; ++$k) {
            if (isset($current0 == $k || $current1 == $k)) continue;
            $result[] = $alphabet[$i].$alphabet[$j].$alphabet[$k];
        }
    }
}

Hope I understood your question right. This one iterates over the alphabet in three loops and always skips the characters which are already used. Then I push the result to $result.

But better try the script with only five letters ;) Using alls strlen($alphabet) (don't wanna count now...) will need incredibly much memory.

(I am sure there is some hacky version which is faster than that, but this is most straightforward I think.)

Upvotes: 0

Artefacto
Artefacto

Reputation: 97835

There's a 1:1 relationship between the permutations of the letters of the alphabet and your sets lists. Basically, once you have a permutation of the alphabet, you just have to call array_chunk to get the sets.

Now, 24! of anything (that is 620448401733239439360000) will never fit in memory (be it RAM or disk), so the best you can do is to generate a number n between 1 and 24! (the permutation number) and then generate such permutation. For this last step, see for example Generation of permutations following Lehmer and Howell and the papers there cited.

Upvotes: 0

Related Questions