
# Step 1: Define the Polybius Grid
# -------------------------------------

# Create a 4x10 Polybius grid for encryption. This grid maps characters to numeric codes.
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)

# Label the rows and columns to easily reference elements in the grid.
rownames(polybius) <- 0:3
colnames(polybius) <- 0:9

# Print the Polybius grid to understand the character mapping.
polybius

# -------------------------------------
# Step 2: Define the Plaintext Message
# -------------------------------------

# Define the message that needs to be encrypted.
plain_message <- "CAPTURETHEFORT"

# Split the message into individual characters by using substring()
char_vector <- sapply(1:nchar(plain_message), function(x) substring(plain_message, x, x))

# -------------------------------------
# Step 3: Initialize Ciphertext Storage
# -------------------------------------
# Create an empty vector to store encrypted codes.
encrypted_text <- c()

# -------------------------------------
# Step 4: Encrypt the Characters
# -------------------------------------

# Iterate over each character in the message and find its corresponding code in the Polybius.
for (char in char_vector) {
  located <- FALSE
  for (row_num in seq_len(nrow(polybius))) {
    if (located) break
    for (col_num in seq_len(ncol(polybius))) {
      if (polybius[row_num, col_num] == char) {
        # Generate the code by combining row and column indices and store it.
        code <- paste0(row_num - 1, col_num - 1)
        encrypted_text <- c(encrypted_text, code)
        located <- TRUE
        break
      }
    }
  }
}

# Step 5: Print the Encrypted Message
# Display the encrypted codes.
encrypted_text

# -------------------------------------
# Step 6: Format the Encrypted Message
# -------------------------------------

# Example of encrypted text generated in previous steps.
encrypted_text <- c("33", "12", "25", "18", "35", "14", "16", "18", "36", "16", "28", "19", "14", "18")

# Combine all encrypted codes into a single string.
encrypted_string <- paste(encrypted_text, collapse = "")

# Split the combined string into segments of 5 characters for better readability.
finaltext <- c()
for (position in seq(1, nchar(encrypted_string), by = 5)) {
  part <- substr(encrypted_string, position, position + 4)
  if (nchar(part) < 5) {
    # Pad with random digits if the segment,if it has fewer than 5 characters.
    part <- paste0(part, paste0(sample(0:9, 5 - nchar(part), replace = TRUE), collapse = ""))
  }
  finaltext <- c(finaltext, part)
}

# Print the final formatted encrypted message.
finaltext
