In [1]:
library(foreach)
In [2]:
data <- read.csv("data.csv",header=F)
data
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!")