# Create the Polybius matrix for the Polybius cipher
# This matrix maps characters to positions for encryption
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)

# Assign row and column labels for reference
rownames(polybius) <- 0:3
colnames(polybius) <- 0:9

# Display the Polybius matrix for verification
print("Polybius Matrix:")
print(polybius)

# Define the plaintext to encrypt
plaintext <- "CAPTURETHEFORT"

# Break the plaintext string into individual characters
message_chars <- strsplit(plaintext, "")[[1]]

# Initialize a vector to store encrypted codes
ciphertext_storage <- c()

# Encrypt each character by finding its position in the Polybius matrix
for (char in message_chars) {
  found <- FALSE # Flag to track if the character is found
  for (row in 1:nrow(polybius)) {
    for (col in 1:ncol(polybius)) {
      if (polybius[row, col] == char) {
        # Combine row and column indices for encryption code
        code <- paste0(row - 1, col - 1)
        ciphertext_storage <- c(ciphertext_storage, code)
        found <- TRUE
        break
      }
    }
    if (found) break
  }
}
ciphertext_storage
# Combine all encryption codes into a single string
ciphertext_combined <- paste(ciphertext_storage, collapse = "")

# Format the ciphertext into groups of 5 characters for better readability
# If the last group has less than 5 characters, pad it with random digits
formatted_ciphertext <- c()

for (i in seq(1, nchar(ciphertext_combined), by = 5)) {
  group <- substr(ciphertext_combined, i, i + 4)
  # Pad the group if it's less than 5 characters
  if (nchar(group) < 5) {
    padding <- paste0(sample(0:9, 5 - nchar(group), replace = TRUE), collapse = "")
    group <- paste0(group, padding)
  }
  formatted_ciphertext <- c(formatted_ciphertext, group)
}

# Display the formatted ciphertext
print("Formatted Ciphertext:")
print(formatted_ciphertext)
