Day 9: Smoke Basin

array = [];
File.foreach("import.dat").with_index do |line, line_num|
  temp = Array(line.strip.chars)
  array.push(temp)
end

grid = []
array.each do |c|
  temp = []
  c.each do |n|
    o = (n.to_i)
    temp.push(o)
  end
  grid.push(temp)
end

x_max = 9
y_max = 4

result = []
grid.each_with_index do |line,index|
  line.each_with_index do |n, i|
    if index == 0  # top

        if i == 0
          if n < line[i+1] && n < grid[index+1][0]
            puts "#{n} is shortest!"
            result.push(n)
          end
        elsif i == x_max
          if n < line[i-1] && n < grid[1][i]
            puts "#{n} is shortest!"
            result.push(n)
          end
        else
          puts line[i+1]
          if n < line[i-1] && n <line[i+1] && n < grid[index+1][i]
            puts "#{n} is shortest!"
            result.push(n)
          end
        end
        #top row end

    elsif index == 4  # last

        if i == 0
          if n < line[i+1] && n < grid[index-1][0]
            puts "#{n} is shortest!"
            result.push(n)
          end
        elsif i == x_max
          if n < line[i-1] && n < grid[y_max-1][i]
            puts "#{n} is shortest!"
            result.push(n)
          end
        else
          if n < line[i-1] && n <line[i+1] && n < grid[index-1][i]
            puts "#{n} is shortest!"
            result.push(n)
          end
        end
        #last row end

    else
      if i == 0
        if n < line[i+1] && n < grid[index-1][0] && n < grid[index+1][0]
          puts "#{n} is shortest!"
          result.push(n)
        end
      elsif i == x_max
        if n < line[i-1] && n < grid[index-1][i] && n < grid[index+1][i]
          puts "#{n} is shortest!"
          result.push(n)
        end
      else
        if n < line[i-1] && n < grid[index-1][i] && n < grid[index+1][i] && n < line[i+1]
          puts "#{n} is shortest!"
          result.push(n)
        end
      end
    end
  end
end

ans = 0
result.each do |n|
  ans =  ans + n + 1
end
puts ans

メモ

Recursive Functionを使う問題。Q2がよくわからなかったので時間ある時に戻って解く。