Logic of all possible mixtures of the values of a variable quantity array. PHP

Asked

Viewed 111 times

0

I’m racking my brain to create a logic that will do the following:

Receive an array of N positions, within these positions define all possible possibilities without repeating the key of a position.

Example: Array('A','B','C')

To AB ABC AC CBA
B BA BAC BC BCA
C CA CAB CB CBA

Examples of the mathematical formula

When there are 3 positions:
3+(3*2)+(3*2*1)
When there are 4 positions:
4+(4*3)+(4*3*2)+(4*3*2*1)

  • I believe I could solve this using n for, being n the amount of variables that will be used

  • A doubt, you have some control over the amount of variables that enter?

  • Yes, you can enter 1 to 10 values and I can identify how many are.

  • 1

    It is difficult to implement this... kkkkkkkk

1 answer

1

If there is control over the amount of variables entering, you can create X structures for, where X is the number of variables in the array, doing something like:

$arr = array("A","B","C");

for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i]."\n";
    for ($j = 0; $j < count($arr); $j++) {
        if ($i != $j) {
            echo $arr[$i].$arr[$j]."\n";
            for ($k = 0; $k < count($arr); $k++) {
                if ($i != $j && $i != $k && $j != $k) {
                    echo $arr[$i].$arr[$j].$arr[$k]."\n";
                }
            }
        }
    }
}

See working on ideone

It’s a more manual process, and it would require a larger amount of coding, I’ll see if I can create something more automated.

  • I have considered this possibility, but I do not think I was clear in my previous comment. I do not define how many values enter, I only know how many, the logic I seek should contain values to be defined after receiving the values of the array. I’m trying to do something using recursion in the for calls. But thank you so much for this reply.

  • @paje I believe that using a hybrid logic using the concept of "binaries" and power of an "n number" (size of your array), you can solve your problem, I am trying to elaborate here

  • I don’t understand what you mean by "binary concept". I’m trying to do almost the same way you did manually, but without the need to include more keys inside the loop.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.