Advertisement
Guest User

Untitled

a guest
Apr 9th, 2012
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. open System
  2. open System.IO
  3. open Microsoft.FSharp.Collections
  4.  
  5. let flip f a b = f b a
  6.  
  7. let diff word1 word2 = Seq.zip word1 word2
  8.                       |> Seq.filter(fun (w1,w2) -> w1 <> w2)
  9.                       |> Seq.length
  10.  
  11. let buildMap ws = let l = Array.length ws - 1
  12.                   seq{ for i in 0..l do
  13.                        for j in i..l do
  14.                        if diff ws.[i] ws.[j] < 2
  15.                        then yield i, j; yield j, i }
  16.                   |> Seq.groupBy(fst)
  17.                   |> Seq.map(fun (k,s) -> k, s |> Seq.map(snd))
  18.                   |> Map.ofSeq
  19.  
  20. type Transmute = {s:int;c:int; h:int list}
  21.  
  22. let transmutes (map:Map<int,_>) start =
  23.     let visit   = Seq.fold(fun a {c=c} -> Set.add c a)
  24.     let next vs curs =
  25.         let nxt c = map.[c.c]
  26.                     |> Seq.filter(flip Set.contains vs >> not)
  27.                     |> Seq.map(fun n -> {s=start;h = c.c::c.h; c = n})
  28.         curs |> Seq.map(nxt) |> Seq.collect(fun n -> n)
  29.     let rec trans vs olds = seq{ yield! olds;
  30.                                  let nvs  = visit vs olds
  31.                                  let news = next nvs olds
  32.                                  if Seq.isEmpty news |> not
  33.                                  then yield! trans nvs news }
  34.     trans Set.empty [{s=start;c=start; h=[]}]
  35.  
  36. let findWay words map (start, target) =
  37.     let s = Array.findIndex ((=)start) words
  38.     let t = Array.findIndex ((=)target) words
  39.     let way = transmutes map s |> Seq.tryFind(fun {c=c} -> c=t)
  40.     match way with | None    -> [] | Some(r) -> r.h
  41.  
  42. let words    = File.ReadAllLines @"C:\words.txt"
  43. let wordsMap = buildMap words
  44. let printWay way = way |> Seq.map(fun i -> words.[i]) |> List.ofSeq
  45.  
  46. //ОРИГИНАЛЬНОЕ ЗАДАНИЕ
  47. ["МУХА","СЛОН"; "ДЕНЬ","НОЧЬ"; "СНЕГ","ВОДА"; "ОТЕЦ", "МАТЬ";
  48.  "РУКА","НОГА"; "ЗИМА","ЛЕТО"; "СВЕТ","ТЬМА"; "ЛИПА", "КЛЁН"]
  49. |> Seq.map(fun (s,e) -> s.ToLower(), e.ToLower())
  50. |> Seq.map(fun p -> p, findWay words wordsMap p |> printWay)
  51. |> Seq.iter(printfn "%A")
  52.  
  53.  
  54. //ДОПОЛНИТЕЛЬНОЕ ЗАДАНИЕ
  55. let mt  = wordsMap |> PSeq.map(fun k -> k.Key)
  56.                    |> PSeq.map(transmutes wordsMap)
  57.                    |> PSeq.collect(fun x -> x)
  58.                    |> PSeq.maxBy(fun x -> x.h.Length)
  59. Console.WriteLine("{0} - {1}: {2} \n", words.[mt.s], words.[mt.c], mt.h.Length)
  60. Console.WriteLine(Seq.reduce(fun a s -> a + " " + s) (printWay mt.h))
  61.  
  62. Console.ReadLine()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement