# Written by Yuxuan Zhao
rm(list = ls())

#Task 2.1

#Create a matrix Polybius that contains the character data.
Polybius <- matrix(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"), 
                   ncol=10, byrow = TRUE, dimnames = list(format(0:3), format(0:9)))

cipher_code<-"24160 63616 14162 61935 14163 71602 26222 33719 18008"
# cipher_code<-"07061 61418 26352 21925 12230 32809 36210 53001 39331 02437 02888"
cipher_code_len <- nchar(cipher_code)+1

# Delete spaces in cipher_code
cipher_code_without_space <- ''
for (x in seq(0, cipher_code_len, by=6)){
  group <- substring(cipher_code, x+1, x+5)
  cipher_code_without_space <- paste(cipher_code_without_space, group, sep = "")
}

# Convert codes to letters
letters <- nchar(cipher_code_without_space)
Message <- ''
for (x in seq(1, letters-1, by=2)){
  num <-  as.numeric(substring(cipher_code_without_space, x, x+1))
  if (num>40){ # Avoid 'subscript out of bounds' caused by random numbers
    break
  }
  Letter <- Polybius[num%/%10+1,num%%10+1] # Get the Letter
  if (is.na(Letter)){ # Avoid NA caused by random numbers
    break
  }
  Message <- paste(Message,Letter, sep = "")
}
print(Message)
