In [1]:
library(foreach)
In [2]:
data <- readLines("data.txt")
data
In [3]:
pad <- matrix(c(1:9), ncol =3, byrow=T)
pad
In [4]:
curX <-2
curY <-2
result <- numeric()
a <- foreach(x=data) %do% {
b <- foreach(y=strsplit(x, "")[[1]]) %do% {
switch(y,
D = {curX <- curX + 1},
L = {curY <- curY - 1},
U = {curX <- curX - 1},
R = {curY <- curY + 1}
)
curX <- max(1,curX)
curX <- min(3,curX)
curY <- max(1,curY)
curY <- min(3,curY)
}
result <- c(result,pad[curX,curY])
}
In [5]:
pad2 <- matrix(c(NA), ncol =7, nrow =7, byrow=T) # Made an oversize table to see when I am out based on value not index
pad2[2,4] <- 1
pad2[3,3:5] <- c(2:4)
pad2[4,2:6] <- c(5:9)
pad2[5,3:5] <- c('A','B','C')
pad2[6,4] <- 'D'
pad2
In [6]:
canMove <- function(x,y) !is.na(pad2[x,y]) #Quick function to verify if we are out of the table
In [7]:
curX <-2
curY <-4
result2 <- numeric()
a <- foreach(x=data) %do% {
b <- foreach(y=strsplit(x, "")[[1]]) %do% {
switch(y,
D = {curX <- if (canMove(curX + 1,curY)) curX + 1 else curX},
L = {curY <- if (canMove(curX,curY - 1)) curY - 1 else curY},
U = {curX <- if (canMove(curX - 1,curY)) curX - 1 else curX},
R = {curY <- if (canMove(curX,curY + 1)) curY + 1 else curY}
)
}
result2 <- c(result2,pad2[curX,curY])
}
In [8]:
cat("Q1 -- The passcode for the door is: ", paste(result,collapse=""),'\n')
cat("Q2 -- The passcode for the funny lock is: ", paste(result2,collapse=""),'\n')
In [ ]: