permuting a string (was Re: Speed)

Alex Tweedly alex at tweedly.net
Wed Aug 27 17:33:19 EDT 2014


I'm going to reply 2 or 3 separate answers ... otherwise it will get 
confusing :-)
Sorry if this overloads anyone trying to delete or ignore the thread 
message by message.

On 27/08/2014 21:15, Beat Cornaz wrote:
> As for the Duplicates :
>
> Alex wrote :
>
>> permut() is the optimized version - optimize simepl cases of 1 or 2 chars, eliminate duplicates as we go.
> Well, it does so, but not completely. First, as I discovered in my own script with eliminating duplicates, it needs the input in the form of the most duplicates in the beginning and then trailing off.
> F.i. 111223 would work , but 112223  or 112333 would not return all of the possible (non duplicate) permutations.
Hmmm - I can't see what it gets wrong in these cases.
Can you be specific about what is missed ?   (maybe off-list)
Thanks.

> Moreover, in the script of Alex, a couple of duplicates slip thru.
> F.I. 1123  gives 14 permutations i.s.o. 12. In the list below, the # are the doubles.
Yeah, sorry - bad optimization on my part.

The lines at fault were
         case 2
             put temp & CR & char 2 of temp & char 1 of temp into t2
             break

and their equivalent at the head of the function. This misses the case 
where the last two chars of the output string are the same (i.e. a 
duplicate in the last two places). Update version of the function 
enclosed below, changing those lines to

          case 2
             put temp into t2
             if char 1 of temp <> char 2 of temp then put  CR & char 2 
of temp & char 1 of temp after t2
             break

Full script follows below.
-- Alex.

function permut pMute
    if the number of chars in pMute = 1 then return pMute
    if the number of chars in pMute = 2 then
       if char 1 of pMute = char 2 of pMute then
          return pMute
       else
          return pMute & CR & char 2 of pMute & char 1 of pMute
       end if
    end if

    put empty into t3
    put empty into tDone
    repeat with i = 1 to the number of chars in pMute
       put char i of pMute into c
       if c is among the chars of tDone then next repeat
       put c after tDone
       put pMute into temp
       delete char i of temp
       switch the the number of chars in temp
          case 1
             put temp into t2
             break
          case 2
             put temp into t2
             if char 1 of temp <> char 2 of temp then put  CR & char 2 
of temp & char 1 of temp after t2
             break
          default
             put permut(temp) into t2
       end switch
       repeat for each line L in t2
          put c & L & CR after t3
       end repeat

    end repeat
    return t3

end permut







More information about the use-livecode mailing list