Fulminating Farmland
Part 1
I got much more tripped up by this than I expected. I have mistlecode::index() but it never does what I actually need which is that but with which(). I should just make it. However, I am quite pleased with my little bit of math for getting the correct distance anyways.
step <- function(index = 1, current = 'r', distance = 0) {
if (index == length(program) + 1) return(distance)
nxt <- pattern[which(pattern == program[index])]
if (current == nxt) {
jump <- 6L
} else {
jump <- which(pattern == nxt) - which(pattern == current)
if (jump < 0) jump <- 6 - abs(jump)
}
step(index + 1, nxt, distance + jump)
}
step()[1] 3529
Part 2
This again took me far too long to figure out. I was trying some nonsense math-based solution using table() and eventually realized I could just make the program a factor() and sort() it to get everything set up then re-use the step() function from above. The levels are just starting with r and then whatever is a distance of 5 away (the farthest it can be without being itself).