Crimin4L
Crimin4L

Reputation: 615

Permute a string by changing case (without affecting numbers)

I am trying to get all possible upper and lower case combinations from a given string, without affecting numbers in said string. I currently found this piece of code that works until you put a number into the sequence:

<?php
if (isset($_GET['word'])) {

    $word = $_GET["word"];

    function permute($input){ 
        $n = strlen($input); 
        
        $max = 1 << $n; 

        $input = strtolower($input); 
        
        for($i = 0; $i < $max; $i++) 
        { 
            $combination = $input; 
            
            for($j = 0; $j < $n; $j++) 
            { 
                if((($i >> $j) & 1) == 1) 
                    $combination[$j] = chr(ord($combination[$j]) - 32); 
            } 
            
            echo $combination . " "; 
        } 
    } 
  
permute($word); 
}
?>

Output of abc1:

enter image description here

Expected output:

abc1 Abc1 aBc1 ABc1 abC1 AbC1 aBC1 ABC1

Upvotes: 1

Views: 111

Answers (1)

Jeto
Jeto

Reputation: 14927

Here's one option using a recursive function, combining permutations for the first character with all possible permutations for the rest of the string:

/**
 * @param string $str
 * @return string[]
 */
function findAllPermutations(string $str): array
{
  if ($str === '') {
    return [];
  }
  if (strlen($str) === 1) {
    return ctype_digit($str) ? [$str] : [strtolower($str), strtoupper($str)];
  }

  $permutations = [];
  foreach (findAllPermutations($str[0]) as $firstCharPermutation) {
    foreach (findAllPermutations(substr($str, 1)) as $restPermutation) {
      $permutations[] = $firstCharPermutation . $restPermutation;
    }
  }

  return $permutations;
}

Usage:

$permutations = findAllPermutations('abc1');
print_r($permutations);
// or, if you want them separated with a space:
echo implode(' ', $permutations);

Demo

Upvotes: 1

Related Questions