# -----------------------------
# #Task 2 Assignment 1
# #Emily Stockdale 1906962
# -----------------------------
  
#Q1 Create a matrix polybius 

#create a vector which indludes the characters within the assignment table this will include NA's 
datavector<-c(NA,"Z","M","D",NA,"K","W","Q",NA,"G","V",NA,"A",NA,"R",NA,"E",NA,"T","O",NA,"J","I","S","B","P","Y",NA,"F",NA,"L",NA,NA,"C",NA,"U","H","N",NA,"X")

#display vector
datavector

#build a matrix callled polybius using the data from datavector
polybius<-matrix(datavector, nrow=4, ncol=10, byrow=T)

#specify row names 0-3
rownames(polybius) <-c(0,1,2,3)  

#specify column names 0-9
colnames(polybius) <-c(0,1,2,3,4,5,6,7,8,9)                                     

#display matrix
polybius

#Q2 Encrypt message: CAPTURETHEHILL

#create vector to display the message in individual characters
message<-c("C","A","P","T","U","R","E","T","H","E","H","I","L","L")

#Display vector
message

#define ciphertext, ciphertext is defined as NULL the values will be added later
ciphertext <- NULL

#display ciphertext 
ciphertext


#loop through each element of the matrix using a nested loop to find the column and row number linked to the desired letter 

#loop needs to loop 3 times, once through the vector 'message' then find each letter row 
##and column number in the matrix and then put those values in a vector called 'ciphertext'

#vector ciphertext should include numbers: 33,12,25,18,35,14,16,18,36,22,03,03

#loop through every element of message then find the letter in matrix
#three loops, one for rows one for columns one for the letters 
#ciphertext is created in the loop and is a vector containing multiple numbers



polybius[is.na(polybius)] <- "" #### may need to amend in loop ?????


#################################### Just Characters CAPTURETHEHILL ####################################
for (a in message){
  for(i in rownames(polybius)){
    for(j in colnames(polybius)){
      if (a==polybius[i,j])
        paste0(polybius[i,j])
    }
  }
}

####################################  Characters With digits match CAPTURETHEHILL ####################################
for (a in message){
  for(i in rownames(polybius)){
    for(j in colnames(polybius)){
      if (a==polybius[i,j]) 
        paste0(message(i,j,polybius[i,j]))
    }
  }
}
####################################  Stored In Vector ####################################  

for (a in message){
  for(i in rownames(polybius)){
    for(j in colnames(polybius)){
      if (a==polybius[i,j])
        ciphertext[a] <- c(paste0(i,j))
      print(ciphertext)
    }
  }
}

#display vector
ciphertext

#error in final loop where repeated characters are not being displayed, CAPTUREHIL.

#q3 - final text will have one element that contains everything split into groups of 5 
 
finaltext<- paste(ciphertext, collapse = "")

finaltext <- sub("\\s+$", "",gsub('(.{5})', '\\1 ', finaltext))
 
#display ciphertext
ciphertext 

#display finaltext
finaltext



