Listing all permutations of a string/integer

后端 未结 29 2739
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:44

A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.

Is there

29条回答
  •  天命终不由人
    2020-11-22 01:21

    Here's a purely functional F# implementation:

    
    let factorial i =
        let rec fact n x =
            match n with
            | 0 -> 1
            | 1 -> x
            | _ -> fact (n-1) (x*n)
        fact i 1
    
    let swap (arr:'a array) i j = [| for k in 0..(arr.Length-1) -> if k = i then arr.[j] elif k = j then arr.[i] else arr.[k] |]
    
    let rec permutation (k:int,j:int) (r:'a array) =
        if j = (r.Length + 1) then r
        else permutation (k/j+1, j+1) (swap r (j-1) (k%j))
    
    let permutations (source:'a array) = seq { for k = 0 to (source |> Array.length |> factorial) - 1 do yield permutation (k,2) source }
    

    Performance can be greatly improved by changing swap to take advantage of the mutable nature of CLR arrays, but this implementation is thread safe with regards to the source array and that may be desirable in some contexts. Also, for arrays with more than 16 elements int must be replaced with types with greater/arbitrary precision as factorial 17 results in an int32 overflow.

提交回复
热议问题