# Create Polybius matrix for the Polybius cipher
polybius <- matrix(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"),
                   nrow = 4, byrow = TRUE)

# Add row and column names for reference
rownames(polybius) <- 0:3
colnames(polybius) <- 0:9

# Display the Polybius matrix
polybius

# Define the text to encrypt
plaintext <- "CAPTURETHEFORT"

# Break the text string into separate characters
message_chars <- sapply(1:nchar(plaintext), function(i) substring(plaintext, i, i))

# Create an empty vector to store encrypted codes
ciphertext_storage <- c()

# Find the position of each character in the Polybius matrix to encrypt
for (char in message_chars) {
  for (a in 1:4) {
    for (b in 1:10) {
      if (polybius[a, b] == char) {
        code <- paste0(a - 1, b - 1)  # Combine row and column values
        ciphertext_storage <- c(ciphertext_storage, code)
      }
    }
  }
}

# Display the encrypted codes
ciphertext_storage

# Combine all codes into one long character string
ciphertext_combined <- paste(ciphertext_storage, collapse = "")

# Split the string into group of 5 numbers for more security.
display_ciphertext <- c()

for (x in seq(1, nchar(ciphertext_combined), by = 5)) {
  groupof5 <- substr(ciphertext_combined, x, x + 4)
  if (nchar(groupof5) < 5) {
    groupof5 <- paste0(groupof5, paste0(sample(0:9, 5 - nchar(groupof5), replace = TRUE), collapse = ""))
  }
  display_ciphertext <- c(display_ciphertext, groupof5)
}

# Display the formatted ciphertext
display_ciphertext
