# This is the code from Linghao Kong. 
# Version 1.0
# Create the matrix
Polybius<-matrix(data = c(" ","Z","M","D"," ","K","W","Q"," ","G",
                          "V"," ","A"," ","R"," ","E"," ","T","O",
                          " ","J","I","S","B","P","Y"," ","F"," ",
                          "L"," "," ","C"," ","U","H","N"," ","X"),
                 ncol = 10,byrow = T)

# Rename the rows and columns
rownames(Polybius)<-c(0:3)
colnames(Polybius)<-c(0:9)

# Display the matrix
Polybius

# Encrypt message
# Split the message
message_original<-"CAPTURETHEHILL"
message_splitted<-NULL
for(i in 1:100){
  char_temp<-substring(message_original,i,i)
  if(char_temp=="")break
  message_splitted<-c(message_splitted,char_temp)
}

# Display the split message
message_splitted

# Cipher the message
ciphertext<-NULL
for(j in seq(message_splitted)){
  for(l in 1:4){
    for(k in 1:10){
      if(message_splitted[j]==Polybius[l,k]){
        ciphertext<-c(ciphertext,l-1,k-1)
      }
    }
  }
}

# Display the ciphertext
ciphertext

# complement the ciphertext
for (i in 1:4){
  if(length(ciphertext)%%5!=0){
    ciphertext<-c(ciphertext,floor(runif(1,min = 0,max = 9)))
  }
  else
    break
}
# Convert to finaltext
finaltext<-NULL
for(m in seq(ciphertext)){
  finaltext<-paste(finaltext,ciphertext[m],sep="")
  if(m%%5==0){
    finaltext<-paste(finaltext," ",sep = "")
  }
}

# Display the finaltext
finaltext

