082 Path sum three ways.sf 997 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/ruby
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 08 August 2016
  5. # Website: https://github.com/trizen
  6. # The minimal path sum in the 5 by 5 matrix below, by starting in any cell
  7. # in the left column and finishing in any cell in the right column, and only
  8. # moving up, down, and right; the sum is equal to 994.
  9. # Find the minimal path sum, in a 31K text file containing a 80 by 80 matrix,
  10. # from the left column to the right column.
  11. # https://projecteuler.net/problem=82
  12. # usage: sidef script.sf < p082_matrix.txt
  13. var matrix = []
  14. ARGF.each { |line|
  15. matrix << line.trim.split(',').map{ .to_n }
  16. }
  17. var end = matrix.end
  18. func path(i, j, prev='ok') is cached {
  19. j >= end && return matrix[i][j]
  20. var paths = []
  21. if (i>0 && prev!='down') {
  22. paths << path(i-1, j, 'up')
  23. }
  24. paths << path(i, j+1)
  25. if (i<end && prev!='up') {
  26. paths << path(i+1, j, 'down')
  27. }
  28. paths.min + matrix[i][j]
  29. }
  30. say (0..end -> map {|i| path(i, 0) }.min)