Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need every permutation of capitalized letters in php

Tags:

php

I want to build an array in php that contains every possible capitalization permutation of a word. so it would be (pseudocode)

function permutate($word){
  for ($i=0; $i<count($word); $i++){
    ...confused here...
    array_push($myArray, $newWord)   
  }
  return $myArray;
}

So say I put in "School" I should get an array back of

{school, School, sChool, SCHool, schOOl, ... SCHOOL}

I know of functions that capitalize the string or the first character, but I am really struggling with how to accomplish this.

like image 899
user2325935 Avatar asked Jan 13 '23 13:01

user2325935


1 Answers

This should do it for you:

function permute($word){
    if(!$word)
        return array($word);
    $permutations = array();
    foreach(permute(substr($word, 1)) as $permutation){
        $lower = strtolower($word[0]);
        $permutations[] = $lower . $permutation;

        $upper = strtoupper($word[0]);
        if($upper !== $lower)
            $permutations[] = $upper . $permutation;
    }
    return $permutations;
}

Codepad Demo

However, for your particular use case there may be a better solution. As there are 2^n permutations for a string of length n. It will be infeasible to run this (or even to generate all those strings using any method at all) on a much longer string.

In reality you should probably be converting strings to one particular case before hashing them, before storing them in the database, if you want to do case-insensitive matching.

like image 184
Paul Avatar answered Jan 31 '23 07:01

Paul