In [1]:
library(foreach)

In [2]:
data <- read.csv("data.csv",header=F)
data


V1V2V3V4V5V6V7V8V9V10...V140V141V142V143V144V145V146V147V148V149
1R5 L2 L1 R1 R3 R3 L3 R3 R4 L2... R1 R2 R2 R2 L1 L1 L2 L5 L3 L1

In [3]:
# Small trim function because there is trailling and leading spaces in the data file
trim <- function (x) gsub("^\\s+|\\s+$", "", x)

In [4]:
curX <-0
curY <-0
face <-0
locations <- matrix(c(0,0), ncol =2)

a <- foreach(x=data) %do% {
    face <- if((substr(trim(x),1,1) == "R")) face+1 else face-1;
    lValue <- strtoi(substr(trim(x),2,nchar(trim(x))));
    
    #SubLoop to add all steps into the location matrix
    b <- foreach(y=1:lValue) %do%{
        switch(face%%4+1, {curX <- curX+1}, {curY <- curY+1}, {curX <- curX-1}, {curY <- curY-1});
        locations <- rbind(locations, c(curX,curY))
    } 
}

HQ <- subset(locations,duplicated(locations))[1,] #Get the first

In [5]:
paste("Q1 -- Shortest path to destination is", (abs(curX) + abs(curY)),"blocks away!")
paste("Q2 -- Shortest path to HQ is", (abs(HQ[1]) + abs(HQ[2])),"blocks away!")


"Q1 -- Shortest path to destination is 287 blocks away!"
"Q2 -- Shortest path to HQ is 133 blocks away!"