Results 1 to 2 of 2

Thread: permutation efficiency

  1. #1
    Join Date
    Jul 2006
    Location
    just north of Boston, MA
    Posts
    1,806
    Thanks
    13
    Thanked 72 Times in 72 Posts

    Default permutation efficiency

    I found a code that would create a permutation, however I was wondering if there was any way that I could make it more efficient?

    Site: http://www.php.happycodings.com/Algorithms/code21.html

    Code:
    PHP Code:
    <? 

    function permutations($letters,$num){ 
        
    $last str_repeat($letters{0},$num); 
        
    $result = array(); 
        while(
    $last != str_repeat(lastchar($letters),$num)){ 
            
    $result[] = $last
            
    $last char_add($letters,$last,$num-1); 
        } 
        
    $result[] = $last
        return 
    $result


    function 
    char_add($digits,$string,$char){ 
        if(
    $string{$char} <> lastchar($digits)){ 
            
    $string{$char} = $digits{strpos($digits,$string{$char})+1}; 
            return 
    $string
        }else{ 
            
    $string changeall($string,$digits{0},$char); 
            return 
    char_add($digits,$string,$char-1); 
        } 


    function 
    lastchar($string){ 
        return 
    $string{strlen($string)-1}; 


    function 
    changeall($string,$char,$start 0,$end 0){ 
        if(
    $end == 0$end strlen($string)-1
        for(
    $i=$start;$i<=$end;$i++){ 
            
    $string{$i} = $char
        } 
        return 
    $string


    // define the parameters
    $all permutations('abcd',3); 
    $count count($all);
    // display the permutation
    for($i=0$i<$count$i++) { 
        echo 
    $all[$i] . "<BR>"
    }

    ?>

  2. #2
    Join Date
    Jan 2008
    Posts
    4,168
    Thanks
    28
    Thanked 628 Times in 624 Posts
    Blog Entries
    1

    Default

    In PHP 6, the <> is being removed (use !=).

    And the {} array support is also being removed.
    Jeremy | jfein.net

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •