149.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. // Tuple3Int ...
  3. type Tuple3Int struct {
  4. _1 int
  5. _2 int
  6. _3 int
  7. }
  8. /**
  9. * Definition for a point.
  10. * type Point struct {
  11. * X int
  12. * Y int
  13. * }
  14. */
  15. func maxPoints(points []Point) (maxPts int) {
  16. xAxisDir := make(map[int]int)
  17. yAxisDir := make(map[int]int)
  18. weight := make(map[Point]int)
  19. for i := range points {
  20. xAxisDir[points[i].X]++
  21. yAxisDir[points[i].Y]++
  22. weight[points[i]]++
  23. }
  24. lines := make(map[Tuple3Int]map[Point]int)
  25. for i := 0; i < len(points); i++ {
  26. for j := i + 1; j < len(points); j++ {
  27. if points[i].X != points[j].X && points[i].Y != points[j].Y {
  28. pair := getParamsOfLine(points[i], points[j])
  29. if _, ok := lines[pair]; !ok {
  30. lines[pair] = make(map[Point]int)
  31. }
  32. if _, ok := lines[pair][points[i]]; !ok {
  33. lines[pair][points[i]] += weight[points[i]]
  34. }
  35. if _, ok := lines[pair][points[j]]; !ok {
  36. lines[pair][points[j]] += weight[points[j]]
  37. }
  38. }
  39. }
  40. }
  41. for _, v := range xAxisDir {
  42. if v > maxPts {
  43. maxPts = v
  44. }
  45. }
  46. for _, v := range yAxisDir {
  47. if v > maxPts {
  48. maxPts = v
  49. }
  50. }
  51. for _, m := range lines {
  52. pts := 0
  53. for _, v := range m {
  54. pts += v
  55. }
  56. if pts > maxPts {
  57. maxPts = pts
  58. }
  59. }
  60. return
  61. }
  62. // Caculate params of given line ay = bx + c, return Tuple3Int{a, b, c}
  63. func getParamsOfLine(p1, p2 Point) Tuple3Int {
  64. y, x := p2.Y-p1.Y, p2.X-p1.X
  65. a, b := x, y
  66. for b != 0 {
  67. a, b = b, a%b
  68. }
  69. return Tuple3Int{x / a, y / a, (x*p1.Y - y*p1.X) / a}
  70. }
  71. // func main() {
  72. // println(maxPoints(
  73. // []Point{{1, 1}, {2, 2}, {1, 1}}))
  74. // println(maxPoints(
  75. // []Point{{1, 1}, {2, 2}, {3, 3}}))
  76. // println(maxPoints(
  77. // []Point{{1, 1}, {3, 2}, {5, 3}, {4, 1}, {2, 3}, {1, 4}}))
  78. // }