Advertisement
mudri

Oxford interview problem #2

Jun 29th, 2013
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Searching for the maximum (http://www.cs.ox.ac.uk/admissions/ugrad/Sample_interview_problems)
  2.  
  3. findMax' _ a b xa xb 0
  4.    | a < b = (xb, b)
  5.    | otherwise = (xa, a)
  6. findMax' f a b xa xb i
  7.     | a < b = let xc = xb + d
  8.               in  findMax' f b (f xc) xb xc (i - 1)
  9.    | otherwise = let xc = xa - d
  10.                  in  findMax' f (f xc) a xc xa (i - 1)
  11.     where d = (xb - xa) * ((sqrt 5) - 1) / 2
  12.  
  13. findMax f = let xa = (3 - sqrt 5) / 2
  14.                 xb = 1 - xa
  15.             in  findMax' f (f xa) (f xb) xa xb
  16.  
  17. {- Explanation
  18. Two values are read at each step.
  19. If the left value is smaller, everything to its left is discarded.
  20. Otherwise, everything to the right of the right value is discarded.
  21. The larger value is passed on to the next step, meaning only 1 new value is taken.
  22.  
  23. |    |  |
  24. b|    |  +
  25. a|    +  |
  26. |    |  |
  27. |____|__|____|
  28. 0   xa  xb   1
  29. b > a, so move right:
  30. |####   | |
  31. a|####   + |
  32. b|####   | +
  33. |####   | |
  34. |_##_|__|_|__|
  35. 0      xa xb 1
  36. Note that old xb and new xa are the same, so no remeasuring takes place.
  37.  
  38. The value xa = (3 - sqrt 5) / 2 comes about through solving:
  39. -----|---|-----
  40. (  x + y + x  ) / x
  41.      ==
  42. ---|-|---
  43. ( x  + y) / y
  44. where x + y + x = 1. The value of d comes about in a similar way, but is based on a given y,
  45. rather than a given 2*x + y.
  46. Both numbers are heavily related to the golden ratio:
  47. (3 - sqrt 5) / 2 == 2 - phi
  48. ((sqrt 5) - 1) / 2 == phi - 1
  49.                   == 1 / phi
  50. -}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement