Permutations

new topic     » topic index » view thread      » older message » newer message

Here's a function that returns the maximum possible
permutations (combinations) of all the top level elements
(which are different from eachother) in a sequence .

-- code starts here (but you knew that, didn't you?).

function faculty (integer i1)
    atom i2
    i2=1
    for n=1 to i1 do
        i2 *= n
    end for
    return i2
end function

function count_elements(sequence s1)
    integer found
    sequence s2, s3
    s2={}
    s3={}
    for n=1 to length(s1) do
        found = 0
        for m=1 to length(s2) do
            if not compare(s1[n],s2[m]) then
                s3[m] += 1
                found=1
            end if
        end for
        if found=0 then
            s2 &= {s1[n]}
            s3 &= 1
        end if
    end for
    s1={}
    for n=1 to length(s3) do
        if s3[n] > 1 then
            s1 &= s3[n]
        end if
    end for
    return s1
end function

global function permutate (sequence s)
    sequence elements
    atom divisor
    divisor = 1
    elements=count_elements(s)
    for n=1 to length(elements) do
        divisor *= faculty (elements[n])
    end for
    return faculty (length(s)) / divisor
end function

--- end

Example:

permutate ("euphoria")

returns 40320 while

permutate("sequence")

(same length) returns only 6720.

Subsequences can of course also be permutated.


Did you know that ... the sentence "how on earth can this function
ever be useful to anyone?" can be recombined in as much as
1.898648171e+55 different ways?


Best Regards,

Tor Gausen

new topic     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu