Skip to content

Instantly share code, notes, and snippets.

@cjavdev
Created December 8, 2022 16:01
Show Gist options
  • Save cjavdev/a152b93c3d2328a6b910eedce01c19ee to your computer and use it in GitHub Desktop.
Save cjavdev/a152b93c3d2328a6b910eedce01c19ee to your computer and use it in GitHub Desktop.
if ARGV.empty?
data = DATA.readlines
else
data = File.readlines(ARGV[0])
end
trees = data
.map(&:chomp)
.map {_1.chars}
.map {_1.map(&:to_i)}
def check_visible(trees, i, j)
height = trees[i][j]
row = trees[i]
col = trees.transpose[j]
return 1 if i == 0 || j == 0 || i == trees.length - 1 || j == trees.first.length - 1
return 1 if height > row[0...j].max
return 1 if height > row[j+1..-1].max
return 1 if height > col[0...i].max
return 1 if height > col[i+1..-1].max
0
end
def visibility(trees)
trees.length.times.flat_map do |i|
trees.first.length.times.map do |j|
check_visible(trees, i, j)
# Part 2
# scenic_score(trees, i, j)
end
end
end
def scenic_score(trees, i, j)
height = trees[i][j]
row = trees[i]
col = trees.transpose[j]
scores = []
# To the left
score = 0
(j-1).downto(0).each do |k|
score += 1
break if row[k] >= height
end
scores << score
# To the right
score = 0
(j+1...trees.first.length).each do |k|
score += 1
break if row[k] >= height
end
scores << score
# Above
score = 0
(i-1).downto(0).each do |k|
score += 1
break if col[k] >= height
end
scores << score
# Below
score = 0
(i+1...trees.length).each do |k|
score += 1
break if col[k] >= height
end
scores << score
scores.inject(:*)
end
if ARGV.empty?
require 'rspec/autorun'
RSpec.describe 'day08' do
it 'works for the example case' do
expect(visibility(trees)).to eq([
[1, 1, 1, 1, 1],
[1, 1, 1, 0, 1],
[1, 1, 0, 1, 1],
[1, 0, 1, 0, 1],
[1, 1, 1, 1, 1],
].flatten)
end
it 'works on the scenic stuff' do
expect(scenic_score(trees, 1, 2)).to eq(4)
expect(scenic_score(trees, 3, 2)).to eq(8)
end
end
end
p visibility(trees)
__END__
30373
25512
65332
33549
35390
@cjavdev
Copy link
Author

cjavdev commented Dec 8, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment