08 Julia
Part I Assignment
Julia feels like a scripting language, you can use its REPL built into the Julia executable or just run
$ julia script.jl
# conveniently read the file into an array of lines
lines = readlines("08.input")
# the border of the forest
count = 2*length(lines[1]) + 2*length(lines) - 4
# iterate over inner rows
for n in 2:length(lines)-1
# the current row
row = lines[n]
# iterate over inner columns
for m in 2:length(row)-1
# the current tree, use ASCII of number as its height
hnm = Int(lines[n][m])
# check the column above the tree
t = true
for i in 1:(n-1)
# compare ASCII values
if Int(lines[i][m]) >= hnm
t = false
# view is blocked, skip
break
end
end
# check the column below
b = true
for i in (n+1):length(lines)
if Int(lines[i][m]) >= hnm
b = false
break
end
end
# check the beginning of the current row
l = true
for i in 1:(m-1)
if Int(lines[n][i]) >= hnm
l = false
break
end
end
# check the rest of the current row
r = true
for i in (m+1):length(row)
if Int(lines[n][i]) >= hnm
r = false
break
end
end
# if visible from any angle, count the tree in
if t || b || r || l
global count += 1
end
end
end
println("Visible trees ", count)
Part II
This time the second part seems to be a bit simpler.
lines = readlines("08.input")
score = 0
for n in 2:length(lines)-1
row = lines[n]
for m in 2:length(row)-1
hnm = Int(lines[n][m])
t = 0 # view up (top)
for i in (n-1):-1:1
t += 1
# count until there is a blocking tree
if Int(lines[i][m]) >= hnm
break
end
end
b = 0 # view down (bottom)
for i in (n+1):length(lines)
b += 1
if Int(lines[i][m]) >= hnm
break
end
end
l = 0 # view left
for i in (m-1):-1:1
l += 1
if Int(lines[n][i]) >= hnm
break
end
end
r = 0 # view right
for i in (m+1):length(row)
r += 1
if Int(lines[n][i]) >= hnm
break
end
end
mult = t * b * r * l
if mult > score
global score = mult
end
end
end
println("Maximum score ", score)
What I learned
- Julia uses Multiple dispatch when choosing the right function compared to Python where the first argument is used to determine the function to be called.
- Julia is very fast, comparable to native C.
- Julia can change it’s code in runtime.
- Arrays are indexed from 1!
- REPL is read-eval-print loop and Julia’s is way more user-friendly than that of Python.
- Julia is very easy to use and have some useful expressions like ranges
n:m
andm:-1:n
.
published: 2022-12-08
last modified: 2023-01-21
https://vit.baisa.cz/notes/code/advent-of-code-2022/08/
last modified: 2023-01-21
https://vit.baisa.cz/notes/code/advent-of-code-2022/08/