018 Maximum path sum I.sf 826 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/ruby
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Website: https://github.com/trizen
  5. # Find the maximum total from top to bottom of the triangle below.
  6. # https://projecteuler.net/problem=18
  7. # Runtime: 0.173s
  8. var data = <<'EOT';
  9. 75
  10. 95 64
  11. 17 47 82
  12. 18 35 87 10
  13. 20 04 82 47 65
  14. 19 01 23 75 03 34
  15. 88 02 77 73 07 63 67
  16. 99 65 04 28 06 16 70 92
  17. 41 41 26 56 83 40 80 70 33
  18. 41 48 72 33 47 32 37 16 94 29
  19. 53 71 44 65 25 43 91 52 97 51 14
  20. 70 11 33 28 77 73 17 78 39 68 17 57
  21. 91 71 52 38 17 14 91 43 58 50 27 29 48
  22. 63 66 04 68 89 53 67 30 73 16 69 87 40 31
  23. 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
  24. EOT
  25. var triangle = data.lines.map{.words.map{.to_i}};
  26. func max_value(i=0, j=0) is cached {
  27. i == triangle.len && return 0;
  28. triangle[i][j] + [max_value(i+1, j), max_value(i+1, j+1)].max;
  29. }
  30. say max_value();