Advent of code Day 13

Goal: recursive move in a 2D plan

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


In [1]:
input <- 1362

In [2]:
size <- 70
floor <- matrix(lapply(c(1:size),function(xx){
    lapply(c(1:size),function(yy){
        y <- xx-1
        x <- yy-1
        #cat("#",x,"-----",y,"#")
        value <- (x*x + 3*x + 2*x*y + y + y*y+ input)
        !sum(intToBits(value)==1)%%2
    })
}))

In [3]:
goDeep <- function(posi, past, dest, currentPath){
    if(any(posi<1 | posi>size)){
        #cat("-------------1-------------")
        return(bestPath+1)        
    }
    if(paste(posi,collapse=";") %in% past){
        #cat("-------------3-------------")
        return(bestPath+1)        
    }
    past <- c(past,paste(posi,collapse=";"))
    if(currentPath>=bestPath){
        #cat("-------------2-------------")
        return(bestPath)        
    }
    #print(past)
    #print(posi)
    if(!floor[[posi[1]]][[posi[2]]]){
        #cat("-------------4-------------")
        return(bestPath)        
    }
    #cat("-------------5-------------")
    if(all(posi==dest)){
        bestPath <<- currentPath
        return(currentPath)
        
    }
    x <- posi[1]
    y <- posi[2]
    a <- goDeep(c(x+1,y),past,dest,currentPath+1)
    c <- goDeep(c(x,y+1),past,dest,currentPath+1)
    b <- goDeep(c(x-1,y),past,dest,currentPath+1)
    d <- goDeep(c(x,y-1),past,dest,currentPath+1)
    return(min(c(a,b,c,d)))
    
}

In [4]:
bestPath <- 150
myPast <- list()
Q1 <- goDeep(c(2,2),myPast,c(40,32),0)
Q1


82

In [5]:
goDeepCounting <- function(posi, currentPath, path){
    if(any(posi<1 | posi>size)){
        #cat("-------------1-------------")
        return(path)       
    }
    if(currentPath>max){
        #cat("-------------2-------------")
        return(path)          
    }
    if(paste(posi,collapse=";") %in% path){
        #cat("-------------3-------------")
        return(path)            
    }
    #print(posi)
    if(!floor[[posi[1]]][[posi[2]]]){
        #cat("-------------4-------------")
        return(path)       
    }
    path <- c(path,paste(posi,collapse=";"))
    x <- posi[1]
    y <- posi[2]
    u <- goDeepCounting(c(x+1,y),currentPath+1, path)
    l <- goDeepCounting(c(x,y+1),currentPath+1, path)
    d <- goDeepCounting(c(x-1,y),currentPath+1, path)
    r <- goDeepCounting(c(x,y-1),currentPath+1, path)   
    return(unique(c(u,l,d,r)))
}

In [6]:
max <- 50
pastQ2 <- goDeepCounting(c(2,2),0,list())
length(pastQ2)


138

In [7]:
cat("Q1- Shortest path to 31,39 is : ", Q1, '\n')
cat("Q2- Number of reachable place under 50 steps: ", length(pastQ2), '\n')


Q1- Shortest path to 31,39 is :  82 
Q2- Number of reachable place under 50 steps:  138