algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

main.ml (1196B)


      1 (*
      2     There are buildings in front of you with heights [a_0,a_1,...,a_{n-1}], where a_i is an integer. Assume each building has a depth of 100 units, there is a 10 unit gap between each of them, they are all directly in front of you, and the ground is flat.
      3 
      4     The first building is 100 units in front of you, and your eyes are 6 units above ground level. How many buildings are visible?
      5 *)
      6 
      7 let readInt () = 
      8     Scanf.scanf " %d" (fun x -> x)
      9 in
     10 
     11 let readInts n = 
     12     let arr = Array.make n 0 in 
     13     let rec acc idx = 
     14         if idx >= n then () else (arr.(idx) <- readInt (); acc (idx+1))
     15     in acc 0; arr
     16 in
     17 
     18 (* we are 6 units tall *)
     19 let angleFromEyeLevel height distance = 
     20     atan ((float_of_int (height - 6)) /. (float_of_int (distance)))
     21 in
     22     
     23 let solve nums = 
     24     let rec acc idx best = 
     25         if idx >= (Array.length nums) then 0 else 
     26             let currentAngle = angleFromEyeLevel nums.(idx) ((idx * 110) + 100)  in
     27                 if currentAngle > best then 
     28                     1 + (acc (idx+1) currentAngle)
     29                 else acc (idx+1) best
     30     in acc 0 0.
     31 in
     32 
     33 let n = readInt () in 
     34     let nums = readInts n in 
     35     print_int (solve nums); print_newline ()