Advent of code Day 23

Goal: Looks to be a clone of day 12. Hint: need to realize the logic of the puzzle (input algo)

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


In [1]:
library("stringr")
options(warn=-1)

In [2]:
instructions <- readLines("data.txt")

In [4]:
getCustomValue <- function(bf,x){
    if (x=='a'|x=='b'|x=='c'|x=='d')
        return(bf[x])
    return(x)
}

In [5]:
position <- 1
buffer <- list(a=7,b=0,c=0,d=0)
while(position <= length(instructions)){
  instruc <- str_split(instructions[position]," ")[[1]]
  switch(instruc[1], 
         cpy={
           if(is.na(as.numeric(instruc[3]))){
             buffer[instruc[3]] <- as.integer(getCustomValue(buffer,instruc[2]))
           }
           else {
             print("------------------")
           }
           position <- position+1
         },
         inc={
           if(is.na(as.numeric(instruc[2]))){
             buffer[instruc[2]] <- as.integer(buffer[instruc[2]]) + 1
           }
           position <- position+1
         },
         dec={
           if(is.na(as.numeric(instruc[2]))){
             buffer[instruc[2]] <- as.integer(buffer[instruc[2]]) - 1
           }  
           position <- position+1
         },
         tgl={
           toChange <- as.integer(getCustomValue(buffer,instruc[2])) + position
           if(toChange<=length(instructions)){
             newInstruct <- str_split(instructions[toChange]," ")[[1]]
             if(length(newInstruct) == 2){
               if (newInstruct[1]=="inc"){
                 newInstruct[1] <- "dec"
               } else {
                 newInstruct[1] <- "inc"
               }
             } else {
               if (newInstruct[1]=="jnz"){
                 newInstruct[1] <- "cpy"
               } else {
                 newInstruct[1] <- "jnz"
               }
             }
             instructions[toChange] <- paste(newInstruct, collapse = " ")
           }
           position <- position+1
         },
         jnz={
           if(as.integer(getCustomValue(buffer,instruc[2]))!=0){
             position <- position + as.integer(getCustomValue(buffer,instruc[3]))
           } 
           
           else{
             position <- position+1
           }
         },
         {
           print('default')
         }
  )
}

In [6]:
buffer['a'][[1]]


12748

Puzzle logic

After trying to run part 2 with the same loop, I reallyse it was almost imposible, after a quick analysis of the algo I realized that it was N Factorial of the input + big number1*big number2 in my case line 20 and 21


In [8]:
egg1 <- 7
big1 <- 94
big2 <- 82
Q1 <- factorial(egg1) + big1*big2
Q1


12748

In [9]:
egg2 <- 12
Q2 <- factorial(egg2) + big1*big2
Q2


479009308

In [9]:
cat("Q1- Value in the A buffer when the egg hint is 7: ", Q1, '\n')
cat("Q2- Value in the A buffer when the egg hint is 12: ", Q2, '\n')


Q1- Value in the A buffer:  318083 
Q2- Value in the A buffer:  9227737