3

I try to get all combination upper and lower case characters of string. For example my string is abc. I need to get result like this, all combinations for 3 characters of string: (2^0) x (2^1) x (2^2) = 8:

abc
Abc
ABc
ABC
aBC
abC
AbC
aBc

My code is this but I have a problem, my code have duplicate cases and not return AbC and aBc:

<?php
function opposite_case($str) 
{ 
    if(ctype_upper($str)) 
    { 
        return strtolower($str); 
    } 
    else 
    { 
        return strtoupper($str); 
    } 
} 

$str = "abc";

for($i = 0 ; $i < strlen($str) ; $i++)
{
    for($j = 0 ; $j < strlen($str) ; $j++) 
    {
        $str[$j] = opposite_case($str[$j]);
        echo $str."<br>"; 
    }
}
?>
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Milad Ghiravani
  • 1,625
  • 23
  • 43

1 Answers1

1

A bit of a code dump with some comments thrown in for good measure. This was converted from the Java implementation - https://stackoverflow.com/a/6785649/296555

http://sandbox.onlinephpfunctions.com/code/aadefa26561a0e33c48fd1d147434db715c8fc59

November 2020 - This answer has was updated in 2 places. See the revision history for details.

<?php

function calculatePermutations($text) {

    $permutations = array();
    $chars = str_split($text);
    
    // Count the number of possible permutations and loop over each group 
    for ($i = 0; $i < 2 ** strlen($text); $i++) {
        
        // Loop over each letter [a,b,c] for each group and switch its case
        for ($j = 0; $j < strlen($text); $j++) {
            
            // isBitSet checks to see if this letter in this group has been checked before
            // read more about it here: http://php.net/manual/en/language.operators.bitwise.php
            $permutations[$i][] = (isBitSet($i, $j)) 
                ? strtoupper($chars[$j]) 
                : $chars[$j];
        }
    }
    
    return $permutations;
}

function isBitSet($n, $offset) {
  return ($n >> $offset & 1) != 0;
}

print_r(calculatePermutations('abc'));
waterloomatt
  • 3,662
  • 1
  • 19
  • 25
  • Thanks dear. A few seconds ago I see this Java comment and convert this to PHP. Thanks again. – Milad Ghiravani Jun 23 '17 at 15:50
  • This is a bit old, but since it's one of the top search results here goes. While the original Java implementation is correct, this one seems to have two bugs. 1) The initial for loop should start at 0, otherwise you'll end up missing the initial string in the results. 2) The number of possible permutations is 2 to the power of the string's length, and not the other way around. – Diogo Teixeira Nov 17 '20 at 11:30
  • @DiogoTeixeira - you are indeed correct. Thanks for pointing it out. I have updated the answer. – waterloomatt Nov 17 '20 at 14:28