# Step 1: Define the Polybius matrix
# The Polybius square is a 4x10 grid of characters used for encryption.
# Each character is assigned a unique position in the grid (row and column).
# Spaces and some letters are included to fill the grid.


Polybius <- matrix(
  c(" ", "Z", "M ", "D", " ", "K", "W", "Q", " ", "G",  # First row
    "V", " ", "A", " ", "R", " ", "E", " ", "T", "O",   # Second row
    " ", "J", "I", "S", "B", "P", "Y", " ", "F", " ",   # Third row
    "L", " ", " ", "C", " ", "U", "H", "N", " ", "X"),  # Fourth row
  nrow = 4, byrow = TRUE  # Specify that the matrix has 4 rows and fill it row by row
)



# Display the Polybius matrix as output to verify its correctness
print("Polybius matrix:")
print(Polybius)



# Assign row and column names for easier reference
# Rows are labeled 0, 1, 2, 3 and columns are labeled 0–9 to simulate the Polybius coordinate system.
rownames(Polybius) <- 0:3
colnames(Polybius) <- 0:9



# Print the Polybius matrix with the assigned row and column names for clarity
Polybius  # Output the matrix



# Step 2: Encrypt the message
# Define the plaintext message to be encrypted
# This is the message we want to encode into a sequence of coordinates.
message <- "CAPTURETHEFORT"



# Break the message into individual characters
# The `substring` function extracts one character at a time and stores them in a vector.
message_vector <- substring(message, 1:nchar(message), 1:nchar(message))



# Print the vector to confirm the message has been split into individual characters
print(message_vector)



# Initialize an empty vector to store the encrypted coordinates (ciphertext)
ciphertext <- c()



# Loop through each character in the message to encrypt it
for (char in message_vector) {
  # Nested loops to iterate through the Polybius matrix
  # Outer loop: Go through each row of the matrix
  for (i in 1:nrow(Polybius)) {
    # Inner loop: Go through each column of the matrix
    for (j in 1:ncol(Polybius)) {
      # Check if the current matrix cell matches the character to be encrypted
      if (Polybius[i, j] == char) {
        # If a match is found, determine its coordinates
        # Adjust row and column indices to be 0-indexed (as specified by Polybius rules)
        code <- paste0(i - 1, j - 1)
        
        # Add the resulting code to the ciphertext vector
        ciphertext <- c(ciphertext, code)
      }
    }
  }
}



# Print the resulting ciphertext as a vector of coordinate pairs
# Each pair represents a character from the original message.
print("Ciphertext vector:")
print(ciphertext)



# Step 3: Format the ciphertext into groups of 5 characters
# Combine the coordinates into a single string for formatting
# The `paste` function joins the elements of the vector into one continuous string.
ciphertext_str <- paste(ciphertext, collapse = "")



# Initialize an empty string to store the final formatted ciphertext
finaltext <- ""



# Split the ciphertext string into groups of 5 characters for readability
# Use a loop to extract substrings of 5 characters at a time.
for (i in seq(1, nchar(ciphertext_str), by = 5)) {
  # Extract a substring of 5 characters starting at position `i`
  group <- substr(ciphertext_str, i, i + 4)
  
  
  
  # If the last group is less than 5 characters, pad it with random digits
  # This ensures all groups have exactly 5 characters.
  if (nchar(group) < 5) {
    # Generate random digits (0–9) to fill the group
    padding <- paste0(sample(0:9, 5 - nchar(group), replace = TRUE), collapse = "")
    group <- paste0(group, padding)  # Add the padding to the group
  }
  
  # Add the formatted group to the finaltext
  finaltext <- c(finaltext, group)
}



# Print the final formatted ciphertext as an array of groups
# Each group contains 5 characters for easier reading.
print("Formatted Finaltext:")
print(finaltext)
