0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

第13回オフラインリアルタイムどう書くの参考問題をF#で

0
Last updated at Posted at 2013-09-01

問題は「増やす減らす二倍する」

ダイクストラ法もどき。副作用を使った書き方を勉強したので2時間以上かかった。
(追記)どうせmutableなら.NETのコレクションを使うことにする。

doukaku13pre.fs
open System.Collections.Generic

let tree = List<_>([[0]])
let set = new HashSet<int>()

let rec find i x =
  let current =
    if i < tree.Count then
      tree.[i]
    else
      let next =
        tree.[tree.Count - 1]
        |> List.collect (fun x -> [x+1; x-1; x*2])
        |> List.filter (fun x -> (x >= 0) && set.Add(x))
      tree.Add(next)
      next
  if List.exists ((=) x) current then i else find (i+1) x

let solve s = (string)(find 0 ((int)s))

(* for test *)

type TestResult = Success | Failure

let test target expected =
  let actual = solve target
  printfn "%A" (if expected = actual then Success else Failure)

[<EntryPoint>]
let main args =
  test "59" "9"
  test "10" "5"
  test "11" "6"
  test "12" "5"
  test "13" "6"
  test "14" "6"
  test "15" "6"
  test "16" "5"
  test "17" "6"
  test "18" "6"
  test "27" "8"
  test "28" "7"
  test "29" "8"
  test "30" "7"
  test "31" "7"
  test "32" "6"
  test "33" "7"
  test "34" "7"
  test "35" "8"
  test "41" "8"
  test "71" "9"
  test "1023" "12"
  test "1024" "11"
  test "1025" "12"
  test "1707" "17"
  test "683" "15"
  test "123" "10"
  test "187" "11"
  test "237" "12"
  test "5267" "18"
  test "6737" "18"
  test "14796" "20"
  test "18998" "20"
  test "23820" "20"
  test "30380" "21"
  test "31119" "21"
  test "33301" "20"
  test "33967" "21"
  test "35443" "22"
  test "35641" "22"
  test "43695" "23"
  test "44395" "23"
  test "44666" "22"
  test "987" "14"
  test "1021" "13"
  test "1019" "13"
  test "1015" "13"
  test "1007" "13"
  test "1011" "14"
  test "1003" "14"
  test "983" "14"
  test "999" "14"
  test "2731" "18"
  test "6827" "20"
  test "10923" "21"
  test "27307" "23"
  test "43691" "24"
  test "109227" "26"
  test "174763" "27"
  0
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?