Advertisement
Guest User

F# EDX Module 4

a guest
Nov 22nd, 2015
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.30 KB | None | 0 0
  1. open System
  2. open System.IO
  3.  
  4. let GetFile() =
  5.     Console.WriteLine("Enter the path to the input file")
  6.     Console.ReadLine()
  7.  
  8. type Point = { X: float; Y: float }
  9.  
  10. type GunTest = {
  11.     Target: Point
  12.     Speed: float
  13.     ExpectedDistance: float
  14.     Name: string
  15. }
  16.  
  17. let gravity = 9.81 //m/s
  18. let CalculateAngleOfReach distance speed = 0.5 * Math.Pow(Math.Sin(gravity * distance / (speed * speed)), -1.0)
  19. let DistanceTravelledOverFlatSurface speed angle = speed * speed * Math.Sin(2.0 * angle) / gravity
  20. let CalculateAngle x y  = Math.Pow(Math.Tan(y / x), -1.0)
  21.  
  22. let (|Hit|Miss|) (gunTest: GunTest) =
  23.     let angle = CalculateAngle gunTest.Target.X gunTest.Target.Y
  24.     let distanceTravelled = DistanceTravelledOverFlatSurface gunTest.Speed angle
  25.     match distanceTravelled >= gunTest.ExpectedDistance with
  26.     | true -> Hit
  27.     | false -> Miss
  28.  
  29. [<EntryPoint>]
  30. let main argv =
  31.  
  32.     try
  33.         use input = new StreamReader(match argv.Length with
  34.                                        | 0 -> GetFile()
  35.                                        | _ -> argv.[0])
  36.        
  37.         let testList = [ while not input.EndOfStream do
  38.                             let raw = input.ReadLine()
  39.                             let values = raw.Split(',')
  40.                                    
  41.                             yield {
  42.                                 Target = { X = float values.[0]; Y = float values.[1] }
  43.                                 Speed = float values.[2]
  44.                                 ExpectedDistance = float values.[3]
  45.                                 Name = values.[4]
  46.                             } ]
  47.  
  48.         for test in testList do
  49.             match test with
  50.             | Hit -> printfn "Gun %s hit the target as expected" test.Name
  51.             | Miss ->
  52.                 let angleOfReach = CalculateAngleOfReach test.ExpectedDistance test.Speed
  53.                 printfn "Gun %s should shoot at angle %f in order to hit the target" test.Name angleOfReach
  54.  
  55.         Console.ReadLine() |> ignore
  56.         0
  57.     with
  58.     | :? FileNotFoundException ->
  59.         printfn "The input file was not found"
  60.         Console.ReadLine() |> ignore
  61.         -1
  62.     | _ ->
  63.         printfn "An error occured while reading the input file. Press any key to exit"
  64.         Console.ReadLine() |> ignore
  65.         -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement