main.jl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Combinatorics
  2. using DelimitedFiles
  3. using BenchmarkTools
  4. #--------part1
  5. function twosum(array)
  6. sort_a = sort(array[:, 1])
  7. for i in sort_a
  8. for j in sort_a
  9. if i + j == 2020
  10. return i * j
  11. end
  12. end
  13. end
  14. end
  15. function ocamlAnton(array)
  16. sort_a = sort(array[:, 1])
  17. i = 1
  18. j = length(sort_a) - 1
  19. while i < j
  20. _sum = sort_a[i] + sort_a[j]
  21. if _sum > 2020
  22. j = j - 1
  23. elseif _sum < 2020
  24. i = i + 1
  25. else
  26. return sort_a[i] * sort_a[j]
  27. end
  28. end
  29. end
  30. function twosumcomb(array)
  31. for pair in combinations(array, 2)
  32. if sum(pair) == 2020
  33. return prod(pair)
  34. end
  35. end
  36. end
  37. #--------part2
  38. function threesum(array)
  39. sort_a = sort(array[:, 1])
  40. for i in sort_a
  41. for j in sort_a
  42. for a in sort_a
  43. if i + j + a == 2020
  44. return i * j * a
  45. end
  46. end
  47. end
  48. end
  49. end
  50. function threesumcomb(array)
  51. for cort in combinations(array, 3)
  52. if sum(cort) == 2020
  53. return prod(cort)
  54. end
  55. end
  56. end
  57. #--------evaluation
  58. selfdir = joinpath(@__DIR__, "input")
  59. array = readdlm(selfdir, Int)
  60. ocaml_result = @btime ocamlAnton(array)
  61. println("ocaml_result = $ocaml_result")
  62. twosum_result = @btime twosum(array)
  63. println("twosum_result = $twosum_result")
  64. twosumcomb_result = @btime twosumcomb(array)
  65. println("twosumcomb_result = $twosumcomb_result")
  66. threesum_result = @btime threesum(array)
  67. println("threesum_result = $threesum_result")
  68. threesumcomb_result = @btime threesumcomb(array)
  69. println("threesumcomb_result = $threesumcomb_result")