Advent of code Day 17

Goal: recursive move in a 2D plan based on MD5s

Ref: http://adventofcode.com/2016/day/17


In [1]:
library(digest)

In [2]:
input <- "rrrbmfta"
longest <- 0
shortest <- 500
shortPath <- input

In [3]:
goIn <- function(posi, path, direction){
  #cat(posi,"--",path,"--",direction,"==",shortest,'\n')
  if(!(direction=='b'||direction=='c'||direction=='d'||direction=='e'||direction=='f')){
    return(0)
  }
  if(nchar(path)>=shortest){
    return(0)
  }
  if(posi==16 && nchar(path)<shortest){
    #cat("*******************")
    #cat(nchar(path),'\n')
    #cat(posi,"--",path,"--",direction,"==",shortest,'\n')
    shortest <<- nchar(path)
    shortPath <<- path
    return(0)
  }
  if (posi<1){
    return(0)
  }
  if (posi>16){
    return(0)
  }
  x <- digest(path,"md5", serialize = FALSE)
  goIn(posi-4,paste(c(path,'U'),collapse=""),substr(x,1,1))#up
  goIn(posi+4,paste(c(path,'D'),collapse=""),substr(x,2,2))#down
  if(posi%%4!=1)
    goIn(posi-1,paste(c(path,'L'),collapse=""),substr(x,3,3))#left
  if(posi%%4!=0)
    goIn(posi+1,paste(c(path,'R'),collapse=""),substr(x,4,4))#right
}

In [4]:
posi <- 1
goIn(1, input, 'b')
Q1 <- shortPath
Q1 <- substr(Q1,nchar(input)+1,nchar(Q1))
Q1


0
"RLRDRDUDDR"

In [5]:
goIn2 <- function(posi, path, direction){
  #cat(posi,"--",path,"--",direction,"==",shortest,'\n')
  if(!(direction=='b'||direction=='c'||direction=='d'||direction=='e'||direction=='f')){
    return(0)
  }
  if(posi==16 && nchar(path)>longest){
    #cat("*******************")
    #cat(nchar(path),'\n')
    #cat(posi,"--",path,"--",direction,"==",longest,'\n')
    longest <<- nchar(path)
    return(0)
  }  
  if(posi==16){
    return(0)
  }
  if (posi<1){
    return(0)
  }
  if (posi>16){
    return(0)
  }
  x <- digest(path,"md5", serialize = FALSE)
  goIn2(posi-4,paste(c(path,'U'),collapse=""),substr(x,1,1))#up
  goIn2(posi+4,paste(c(path,'D'),collapse=""),substr(x,2,2))#down
  if(posi%%4!=1)
    goIn2(posi-1,paste(c(path,'L'),collapse=""),substr(x,3,3))#left
  if(posi%%4!=0)
    goIn2(posi+1,paste(c(path,'R'),collapse=""),substr(x,4,4))#right
}

In [6]:
goIn2(1, input, 'b')
Q2 <- (longest -8)
Q2


0
420

In [7]:
cat("Q1- Shortest path to the vault is : ", Q1, '\n')
cat("Q2- Longest path to the vault is : ", Q2, '\n')


Q1- Shortest path to the vault is :  RLRDRDUDDR 
Q2- Longest path to the vault is :  420