Once I realized that moves on a hex grid map nicely to a standard rectangular grid, this was easy. Despite playing hours of *Settlers of Catan*, I’d never realized this relationship. Maybe because nothing traverses that hex grid?

North and South move one step up or down. The four diagonal directions move a half-step up or down and a full column laterally. The shortest solution path will be diagonal moves to reach the desired column, then vertical moves to the right row.

It took only a minute or two to modify my part 1 function for part 2, so I present both together.

### Parts 1 & 2

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 |
library(dplyr); library(testthat) steps_needed <- function(dat){ lat <- 0 lon <- 0 max_dist <- 0 current_dist <- 0 for(i in seq_along(dat)){ if(dat[i] == "n"){lat <- lat + 1} if(dat[i] == "s"){lat <- lat - 1} if(dat[i] == "ne"){lat <- lat + 0.5; lon <- lon + 1} if(dat[i] == "se"){lat <- lat - 0.5; lon <- lon + 1} if(dat[i] == "nw"){lat <- lat + 0.5; lon <- lon - 1} if(dat[i] == "sw"){lat <- lat - 0.5; lon <- lon - 1} current_distance <- abs(lon) + # diagonal steps to move horizontally abs(lat) - 0.5 * abs(lon) # vertical steps, adjusted for prev diagonal moves max_dist <- max(c(max_dist), current_distance) current_dist <- current_distance } structure(c(current_dist, max_dist), names = c("Current Distance", "Maximum Distance")) } # Tests expect_equal(steps_needed(c("se","sw","se","sw","sw")), 3) expect_equal(steps_needed(c("ne", "ne", "ne")), 3) expect_equal(steps_needed(c("ne", "ne", "sw", "sw")), 0) expect_equal(steps_needed(c("ne", "ne", "s", "s")), 2) # Execute dat <- unlist(str_split(scan("11_1_dat.txt", "character"), ",")) steps_needed(dat) # Current Distance Maximum Distance # 722 1551 |