In [1]:
    
library("stringr")
options(warn=-1)
    
In [2]:
    
instructions <- readLines("data.txt")
wantedOutput <- paste(rep("01",20),collapse="")
    
In [3]:
    
getCustomValue <- function(bf,x){
    if (x=='a'|x=='b'|x=='c'|x=='d')
        return(bf[x])
    return(x)
}
    
In [4]:
    
cat("Q1- Value in the A buffer to get the pattern is 196 ",'\n')
    
    
In [5]:
    
current <- 190
found <- FALSE
while(!found){
  currentOutput <- ""
  position <- 1
  buffer <- list(a=current,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
           },
           out={
             vv <- getCustomValue(buffer,instruc[2])
             currentOutput <- paste(c(currentOutput,vv),collapse="")
             if(!startsWith(wantedOutput,currentOutput)){
               current <<- current + 1
               break
             } else if(nchar(currentOutput)>30){
               found <- TRUE
               break
             }
             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')
           }
    )
  }
}
current