In [1]:
library(foreach)
library(stringr)
In [2]:
data <- readLines("data.txt")
str(data)
In [15]:
ttt <- str_match(data,"(.*)\\-+(\\d+)\\[(.*)\\]")
head(ttt)
In [3]:
parsedData <- gsub("(.*)\\-+(\\d+)\\[(.*)\\]", '\\1:\\2:\\3', data, perl = TRUE)
parsedData <- strsplit(parsedData, ':')
head(parsedData)
In [4]:
dataf <- as.data.frame(matrix(unlist(parsedData), ncol = 3, byrow=T))
colnames(dataf)<- c("code","value","checksum")
head(dataf)
In [5]:
# Simple parsing in int of the value column
dataf$value <- strtoi(dataf$value, base = 0L)
In [6]:
dataf$Valid <- apply(dataf, 1, function(x) {
a<-(sort(table(strsplit(gsub("-","",x[1]),"")), decreasing = TRUE)[1:5])
paste(attributes(a)$dimnames[[1]], collapse = '') == x[3]
})
In [7]:
sum(dataf$value) # Complete Sum
sum(dataf$value[dataf$Valid]) #Sum when Valid
Stolen with pride from: https://github.com/johnmyleswhite/JuliaVsR/blob/master/cipher/cipher.R
In [8]:
english.letters <- c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z')
caesar.cipher <- list()
for (index in 1:length(english.letters))
{
caesar.cipher[[english.letters[index]]] <- english.letters[index %% 26 + 1]
}
caesar.cipher[['-']] <- '-'
In [9]:
apply.cipher.to.string <- function(string, cipher)
{
output <- ''
for (i in 1:nchar(string))
{
output <- paste(output, cipher[[substr(string, i, i)]], sep = '')
}
return(output)
}
In [10]:
tmp <- "northpole-object-storage"
possible <- foreach(x=1:26) %do% {
tmp <- apply.cipher.to.string(tmp, caesar.cipher)
#intersect(strsplit(tmp,'-')[[1]], words)
#if( intersect(strsplit(tmp,'-')[[1]], words) != "")
# strsplit(tmp,'-')[[1]][1]
}
dataf$value[dataf$code==intersect(possible,dataf$code)]
In [11]:
paste("Q1 -- Number of good room is ", sum(dataf$value[dataf$Valid]))
paste("Q2 -- Value of the north pole storage room is ", dataf$value[dataf$code==intersect(possible,dataf$code)])
In [12]:
#words <- readLines("words.txt")
In [13]:
#a <- apply(dataf, 1, function(x) {
# output <- ""
# tmp <-x[1]
# possible <- foreach(x=1:26) %do% {
# tmp <- apply.cipher.to.string(tmp, caesar.cipher)
# #intersect(strsplit(tmp,'-')[[1]], words)
# if(sum((intersect(strsplit(tmp,'-')[[1]], words)) != "")>0)
# output <- tmp
# }
# output
#})
# a