dwvaxaz
dwvaxaz

Reputation: 49

Generating combinations with PHP

So I have the following characters (alt symbols):

¯ ˜ ” “ ’ ‘ ¨ ´ ¹ ² ³ ` ° ⁿ

What I'm trying to do is simple: generate all possible combinations between them up to the length of two. That being said, few sample generations would look like so:

¯ ^ ¨ ³ ^ “

Also they need be seperated by let's say the XOR operator. I was thinking about the following scenario:

$array = array('¯', '˜' ,'”', '“', '’', '‘', '¨', '´', '¹', '²', '³', '`', '°', 'ⁿ');

foreach ($array as $element) {
    echo $element ' ^ ' //..;
}

I just can't actualize my logic. How can I group them in pairs of two elements and go over each possible combination between them without duplicates?

EDIT:


Though I managed to get it working with regular letters like so:

<?php
ini_set('max_execution_time', '65');

$values = 'ABCD';
container(strlen($values), 0 );

function container($length, $pos, $out = '' ){
    global $values;

    for ($i = 0; $i < $length; ++$i){
  if ($pos < $length ){
    container($length, $pos + 1, $out . $values[$i]);
  }
    }

    if(strlen($out) <= 2){
  echo $out . '<br />';
  }
}

?>

I am ending in a deadlock when using the alt symbols as the values for the iteration.

Upvotes: 1

Views: 88

Answers (1)

Marc B
Marc B

Reputation: 360702

Using some different chars:

$chars = array('a','b','c','d','e','f');
for ($i = 0; $i < (count($chars) - 1); $i++) {   // count()-1 to prevent f^f
    for ($j = $i+1; $j < count($chars); $j++) {  // $i+1 to prevent a^a 
        echo "$chars[$i] ^ $chars[$j]\n";
    }
}

Output:

a ^ b
a ^ c
a ^ d
a ^ e
a ^ f
b ^ c
b ^ d
b ^ e
b ^ f
c ^ d
c ^ e
c ^ f
d ^ e
d ^ f
e ^ f

This is presuming that a ^ a is a dupe, and b^a and a^b are dupes of each other.

Upvotes: 0

Related Questions