# title£ºDecrypt message with the specific way
# purpose: the code for Task2.1
# author: Siyu Chen
# Date: 2021/12/1

# Task2.1
# recreate matrix as the same as Task1
Polybius<-matrix(nrow=4,ncol=10)
# input the elements of per rows
Polybius[1,]<-c(NA,'Z','M','D',NA,'K','W','Q',NA,'G')
Polybius[2,]<-c('V',NA,'A',NA,'R',NA,'E',NA,'T','O')
Polybius[3,]<-c(NA,'J','I','S','B','P','Y',NA,'F',NA)
Polybius[4,]<-c('L',NA,NA,'C',NA,'U','H','N',NA,'X')
# create numerical labels of rows and columns
rownames(Polybius)<-c(0:3)
colnames(Polybius)<-c(0:9)
# display the matrix
Polybius

# read ciphertext
ciphertext<-c(2,4,1,6,0,
              6,3,6,1,6,
              1,4,1,6,2,
              6,1,9,3,5,
              1,4,1,6,3,
              7,1,6,0,2,
              2,6,2,2,2,
              3,3,7,1,9,
              1,8,0,0,8
              )
# let the length of ciphertext to be even
len=length(ciphertext)-(length(ciphertext)%%2)
# seperate row-coordinate and column-coordinate
ciphertext_x=NULL
ciphertext_y=NULL
for(i in 1:len){
  if(!i%%2==0){
    ciphertext_x<-c(ciphertext_x,ciphertext[i])
  }else{
    ciphertext_y<-c(ciphertext_y,ciphertext[i])
  }
}
# decipher the message
message_temp=NULL
for(i in seq(ciphertext_x)){
  message_temp<-c(message_temp,Polybius[ciphertext_x[i]+1,ciphertext_y[i]+1])
}
message_temp
# filter the NA
message_temp2<-NULL
for(i in seq(message_temp)){
  if(!is.na(message_temp[i])){
    message_temp2<-c(message_temp2,message_temp[i])
  }
}
message_temp2
# convert it to a vector which contains one element that holds the entire message
plaintext<-paste(message_temp2,collapse="")
plaintext
