aboutsummaryrefslogtreecommitdiff
path: root/day14/part2.rb
blob: cb6f059ddf7930229cc0cc043fdfe6ce6d1b64c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
solids = Hash.new { |h, k| h[k] = Array.new }

$stdin.readlines.map { |line|
  line.strip.split(' -> ').map {
    |coord| coord.split(?,).map(&:to_i)
  }
}.each { |path|
  (path.length - 1).times { |i|
    if path[i][0] == path[i+1][0]
      x = path[i][0]
      y1 = path[i][1]
      y2 = path[i+1][1]
      if y1 > y2
        t = y2
        y2 = y1
        y1 = t
      end
      (y1..y2).each { |y| solids[y] << x }
    else
      x1 = path[i][0]
      x2 = path[i+1][0]
      if x1 > x2
        t = x2
        x2 = x1
        x1 = t
      end
      y = path[i][1]
      (x1..x2).each { |x| solids[y] << x }
    end
  }
}

solids.keys.each { |k| solids[k].uniq!  }

floor = solids.keys.flatten.max + 1

sands = 0
loop do
  sandx = 500
  sandy = 0

  loop do
    break if sandy == floor

    r = solids[sandy + 1]
    if r.include?(sandx)
      if r.include?(sandx - 1)
        if r.include?(sandx + 1)
          break
        else
          sandx += 1
        end
      else
        sandx -= 1
      end
    end
    sandy += 1
  end

  solids[sandy] << sandx
  sands += 1

  break if sandx == 500 && sandy == 0
end

puts sands