mathutil.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package mathutil
  2. import (
  3. "math"
  4. "sync"
  5. )
  6. // intSearch is a mechanism for searching integers in a specific direction
  7. // for a given distance.
  8. type intSearch struct {
  9. value int
  10. distance int
  11. increment int
  12. }
  13. func newIntSearch(value int, increment int) *intSearch {
  14. return &intSearch{
  15. value: value,
  16. distance: 0,
  17. increment: increment,
  18. }
  19. }
  20. func (i *intSearch) advance() {
  21. i.value += i.increment
  22. i.distance++
  23. }
  24. func Approximately(exp, act float64) bool {
  25. return ApproximatelyPct(exp, act, 0.0001) // within 0.1%
  26. }
  27. func ApproximatelyPct(exp, act, pct float64) bool {
  28. delta := exp * pct
  29. if delta < 0.00001 {
  30. delta = 0.00001
  31. }
  32. return math.Abs(exp-act) < delta
  33. }
  34. // FindClosestDivisor finds the closest divisor into the `into` value starting with the `current` value.
  35. // It runs concurrent searches in both directions and returns the value that travels the least distance.
  36. // If the distances are equivalent, it returns the greater value.
  37. func FindClosestDivisor(current int, into int) int {
  38. if isDivisibleBy(current, into) {
  39. return current
  40. }
  41. // we run forward and backwards searches
  42. var wg sync.WaitGroup
  43. wg.Add(2)
  44. // find just advances until it finds a number that can divide cleanly into
  45. // the target int
  46. find := func(res *intSearch) {
  47. defer wg.Done()
  48. for !isDivisibleBy(res.value, into) {
  49. res.advance()
  50. }
  51. }
  52. rev := newIntSearch(current, -1)
  53. fwd := newIntSearch(current, 1)
  54. go find(rev)
  55. go find(fwd)
  56. wg.Wait()
  57. if rev.distance < fwd.distance {
  58. return rev.value
  59. }
  60. return fwd.value
  61. }
  62. // is b divisible by a
  63. func isDivisibleBy(a, b int) bool {
  64. return (a == 0 || b == 0) || (b%a == 0)
  65. }