-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday8_2.rb
More file actions
122 lines (105 loc) · 3.06 KB
/
day8_2.rb
File metadata and controls
122 lines (105 loc) · 3.06 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class Forest
def initialize(input)
@forest = input_file(input)
@best_view = find_best_view(@forest)
end
attr_reader :best_view
def input_file(input)
forest = Array.new
i = 0
File.foreach(input) do |row|
row = row.gsub("\n", "")
forest.push(row.split(//).map{|char| char.to_i})
i += 1
end
return forest
end
def find_best_view(forest)
best_view = 0
forest.each_index do |row|
forest[row].each_index do |column|
# puts "[#{row}, #{column}] = #{forest[row][column]}"
view = view_from_tree(forest, row, column)
# puts viewable
if view > best_view
best_view = view
end
end
end
return best_view
end
def view_from_tree(forest, row, column)
east = view_to_east?(forest, row, column)
west = view_to_west?(forest, row, column)
north = view_to_north?(forest, row, column)
south = view_to_south?(forest, row, column)
# p "[#{row},#{column}] north = #{north}"
# p "[#{row},#{column}] south = #{south}"
# p "[#{row},#{column}] east = #{east}"
# p "[#{row},#{column}] west = #{west}"
# p "#{east * west * north * south}"
return east * west * north * south
end
def view_to_east?(forest, row, column)
#get height of tree
height = forest[row][column]
range = 0..column - 1
view_count = 0
range.reverse_each do |col|
if forest[row][col] >= height
view_count += 1
break
else
view_count += 1
end
end
return view_count
end
def view_to_west?(forest, row, column)
#get height of tree
height = forest[row][column]
range = (column + 1)..(forest[row].length - 1)
view_count = 0
range.each do |col|
if forest[row][col] >= height
view_count += 1
break
else
view_count += 1
end
end
return view_count
end
def view_to_north?(forest, row, column)
#get height of tree
height = forest[row][column]
range = 0..(row - 1)
view_count = 0
range.reverse_each do |row|
if forest[row][column] >= height
view_count += 1
break
else
view_count += 1
end
end
return view_count
end
def view_to_south?(forest, row, column)
#get height of tree
height = forest[row][column]
range = (row + 1)..(forest.length - 1)
view_count = 0
range.each do |row|
if forest[row][column] >= height
view_count += 1
break
else
view_count += 1
end
end
return view_count
end
end
today = Forest.new("day8i.txt")
p today.best_view