2017-12-06 2 views
1

내 프로그램의 속도를 개선하는 방법을 생각하려고하고 있는데, 그 중 하나는 아나그램 생성입니다. 이 경우 비동기 기능이 도움이됩니까 아니면 문자열을 조작하는 또 다른 기술이 있습니까? 이 조금 더 빨리 만들 수F # Async를 사용한 Anagram 생성

let anagramWords = [|"rolex";"viagra";"win";"free";"cash";"grand";"prize"; 
        "nude";"porn";"casino";"lottery";"spins";"sex";"gold"; "buy"; "clearance"; 
        "business"; "biz"; "money"; "opportunity"; "earn"; "extra"; "potential"; "sleep"; "discount"; 
        "bargain"; "credit"; "affordable"; "loans"; "mortages"; "quote"; "dollars"; "invest"; "investment"; 
        "bitcoin"; "silver"; "save"; "unsecured"; "pennies"; "million"; "billion";"bureaus";"stock"; 
        "bankruptcy"; "eliminate"; "debt"; "billing"; "iphone"; "selling"; "obligation";"trial"; 
        "vacation"; "winner";"membership"; "preview"; "sample"; "priority"; "website"; "gift"; "gifts"; 
        "present"; "deal"; "fantastic"; "outstanding"; "values"; "act"; "lifetime"; "urgent"|] 



let rec distribute e = function 
    | [] -> [[e]] 
    | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs] 

let rec permute = function 
    | [] -> [[]] 
    | e::xs -> List.collect (distribute e) (permute xs) 

let genAnagrams word = 
    word 
    |>List.ofSeq 
    |>permute 
    |> List.map (fun x -> String(x |> Array.ofList)) 
    |> Seq.ofList 
    |> Seq.toList 

답변

1

한 매우 간단한 방법 대신 목록의 permute 사용 배열을하고 Array.Parallel.collect 대신 List.collect을 사용하는 것입니다. 배열을 벗어나는 비효율적 인 경우에도 10 자의 단어에 대해 30 % 나 더 빠릅니다.

open System 

let rec distribute e = function 
    | [] -> [[e]] 
    | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs] 

let arrayHeadTail = function [||] -> None | xs -> Some (xs.[0], Array.tail xs) 

let rec permute xs = 
    match arrayHeadTail xs with 
    | None -> [| [] |] 
    | Some (e, xs) -> Array.Parallel.collect (distribute e >> List.toArray) (permute xs) 

let genAnagrams word = 
    word 
    |> Seq.toArray 
    |> permute 
    |> Array.map String.Concat<char> 
+0

어쨌든 CPU 코어 사이의 생성 과정을 분할하는 내 코드를 컴파일하는 데 오랜 시간이 .. 걸리지 만이 가능하기 때문에이 방법은 늘 주요 속도 변화를 줄? –